开发者

Generic callbacks for Static Variables in PHP

开发者 https://www.devze.com 2023-02-16 15:10 出处:网络
I need a way to access a static variable for a class using a variable as the classname. Due to how PHP handles static methods and inheritance, I need to access the variable itself and not a static fun

I need a way to access a static variable for a class using a variable as the classname. Due to how PHP handles static methods and inheritance, I need to access the variable itself and not a static function开发者_运维百科.

class Item
{
   public static $name = 'parent';
}

class SubItem extends item
{
   public static $name = 'child';
}

$classname = 'SubItem';

// This won't work
$value = $classname::$name;

// This obviously won't work either. Not a function.
$value = call_user_func(array($classname, '$name'));

The nature of how PHP handles static methods, an attempt to define a static method in the class Item will always return "parent" instead of "child" if called for the class SubItem.

I'm assuming there's a way, but my reading hasn't providing anything of use.


As a matter of fact, this line :

// This won't work
$value = $classname::$name;

should not work with PHP 5.2, but works with PHP 5.3 : if I use var_dump() on $value, I get the following result

string 'child' (length=5)


I think your answer is here : PHP 5.3 ; it'll solve :

  • The $classname::$name problem (quoting) :

As of PHP 5.3.0, it's possible to reference the class using a variable.
The variable's value can not be a keyword (e.g. self, parent and static).

  • and it should also solve the "define a static method in the class Item will always return "parent" instead of "child"" problem, if you use static instead of self : with PHP 5.3, the static keyword has a new meaning -- see Late Static Binding.


class Item
{
   public static $name = 'parent';

   public function getName(){
     return static::$name;
   }
}

class SubItem extends Item
{
   public static $name = 'child';
}

$classname = 'SubItem';

$value = call_user_func(array($classname, 'getName'));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号