Re: $result = $className::$methodName(); - possible?

From: Ashmodai (ashmodai_at_mushroom-cloud.com)
Date: 01/30/05


Date: Sun, 30 Jan 2005 03:39:25 +0100
To: Joshua Beall <jbeall@donotspam.remove.me.heraldic.us>

Joshua Beall scribbled something along the lines of:
> Hi All,
>
> I have been trying to dynamically call a static member function, as follows:
>
> $className = 'MyClass';
> $methodName = 'MyMethod'
> $result = $className::$methodName();
>
> However, I get a parse error when I do this:
>
> Parse error: parse error, unexpected T_PAAMAYIM_NEKUDOTAYIM in
> /home/HE/web_develop/ghea/www/cgi-bin/lib/EventRegistrationBridgerClasses.inc
> on line 28
>
> Line 28 is indeed the line in which $result = $className::$methodName();
> appears.
>
> Is there any way to do what I am trying to do? I have had success
> dynamically calling methods on known classes. E.g.,
>
> $methodName = 'MyMethod';
> $result = MyClass::$methodName();
>
> This works fine. What if I want to have the class name dynamically defined
> as well? Is there any way to do that?
>
> Thanks for any pointers!
>
>

The problem is that $className::$methodName() results in an error simply
because $className is a string, not an object.
$$className won't work because $MyClass is an undefined variable and not
an object.

I think eval() might solve that.
Try something like

eval($className.'::'.$methodName.'();');

This *should* translate the string into

MyClass::MyMethod();

and execute it.

I'm sure that eval() will help you out but I haven't tested this.

--
Ashmo


Relevant Pages

  • Re: make a class sortable
    ... public MyClass(string className, string classType) ... public static int CompareByClassNameAsc(MyClass a, ... public class MyClass: IComparable ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: Create Forms via Parameter
    ... need the classname to retrieve a class registered via RegisterClasses. ... Function ShowFormByName(const formname: String; ... variable, the form reference, and that can be had the way shown above. ... The VCL contains a suitable class registry, ...
    (borland.public.delphi.language.objectpascal)
  • Re: DirectCom.dll: vb sample -> vfp
    ... GETINSTANCE erwartet als String-Parameter jeweils den Pointer ... Dim D As Object, FName As String, ClassName As String ... ClassName = StrConv'nach ANSI ...
    (microsoft.public.de.fox)
  • Re: String problem VS 2005
    ... the console the Classname and the text in the notepad window. ... The first output to the console is "N" and not ... I dont understand how to work with all the C++ string format. ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Falsch Typ Erkennung ?
    ... Ich habe auch schon mit NHibernate gearbeitet. ... linke Seite immer ein "object" Typ deklariert. ... foreach(string className in classNames) ... object list = NHibernateMethod(className); ...
    (microsoft.public.de.german.entwickler.dotnet.csharp)