Reply to Re: Accessing constant and static members of a class name held in a variable

Your name:

Reply:


Posted by ZeldorBlat on 11/05/80 11:41

Rafe Culpin wrote:
> Does anyone please know of a way to access static methods of a class, when
> the name of that class is held in a variable?
>
> I have several classes (PHP5) which all have identically named methods and
> members.
>
> I want to pass the name of one of the classes to an included file which
> does some standard operations using those methods and members. (So several
> different programs can include that file, each passing a different class
> name.)
>
> I am doing this by putting the name of one of the classes in a variable
> which is passed to the included file. So for example:
> $classname = 'Foo';
>
> $instance = new $classname();
> $instance->do_method($id);
>
> That all works fine.
>
> But how do I access static methods and constant members of the class?
>
> $classname::static_method()
> and
> $classname::MY_CONSTANT
> both give errors. Every variation I've tried gives an error. Is there
> something I'm missing in the syntax which will let me do this? Or maybe a
> different method of passing the name, or of approaching the while thing?
>
> I've found two ways of kludgeing round the problem. One is to use eval()
> round everything, and the other (untested) is to use Reflection. But
> surely there's a less messy way?
>
> --
> To reply email rafe, at the address cix co uk

You can get to them using call_user_func() and constant() like this:

class foo {
const BAR = 5;
public static function baz() {
//do something static
}
}

$myClassName = 'foo';
$bar = constant($myClassName . '::BAR');
$z = call_user_func(array($myClassName, 'baz'));

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация