如何访问对象的静态属性,该对象本身是另一个对象的属性?

时间:2015-10-27 13:43:56

标签: php object static-members

在PHP中,是否可以使用下面类似的语法访问本身是另一个对象的属性的对象的静态属性:

<?php
class Foo
{
    public $bar;
    function __construct()
    {
        $this->bar = new Bar();
    }
}

class Bar
{
    const TEST = 123;
    function __construct() {}
}

$bar = new Bar();
$foo = new Foo();

echo Bar::TEST; // ok
echo $bar::TEST; // ok
echo $foo->bar::TEST; // error
?>

3 个答案:

答案 0 :(得分:2)

将属性分配给变量。

$foo = new Foo();
$bar = $foo->bar;
echo $bar::TEST; // that's good.

答案 1 :(得分:1)

使用Late Static Binding而不是继承该属性可能会更好。所以它会是这样的(改为上面PHP手册页中的一个例子):

<?php
class A
{
  public static function who() 
  {
    echo __CLASS__;
  }
  public static function test() 
  {
    static ::who();
     // Here comes Late Static Bindings

  }
}

class B extends A
{
  public static function who() 
  {
    echo __CLASS__;
  }
}

B::test();
?>

这是另一个可能相关或有用的主题:PHP Inheritance and Static Methods and Properties

答案 2 :(得分:1)

更棘手,但您可以使用 ReflectionClass

echo (new ReflectionClass(get_class($foo->bar)))->getconstant("TEST");
相关问题