从属性引用中获取类名


Getting a class name from a property reference

我想知道你是否可以从PHP的属性引用中获得类名和属性名?

class Test {
    public static $TestProp;
}
GetDoc(& Test::$TestProp);
function GetDoc($prop) {
    $className = getClassName($prop);
    $propertyName = getPropertyName($prop);
}

我要找的是,如果有可能创建函数getClassName和getPropertyName?

你想要的基本上是不可能的;属性不知道它的父结构

我能想到的唯一相同的事情就是对它使用反射:

class Test
{
    public static $TestProp = '123';
}
//GetDoc(& Test::$TestProp);
GetDoc('Test', 'TestProp');
function GetDoc($className, $propName)
{
    $rc = new ReflectionClass($className);
    $propValue = $rc->getStaticPropertyValue($propName);
}

Test类中,您可以使用__CLASS__作为类名的方便引用。

我已经找到了让这个工作的方法有很多神奇的事情要做,但在我的情况下,这是值得的。

class Test {
    private $props = array();
    function __get($name) {
       return new Property(get_called_class(), $name, $this->props[$name]);
    }
    function __set($name, $value) {
       $props[$name] = $value;
    }
}
class Property {
    public $name;
    public $class;
    public $value;
    function __construct($class, $name, $value) {
        $this->name = $name;
        $this->class = $class;
        $this->value = $value;
    }
    function __toString() {
        return $value.'';
    }
}
function GetClassByProperty($prop) {
    return $prop->class.'->'.$prop->name;
}
$t = new Test();
$t->Name = "Test";
echo GetClassByProperty($t->Name);

这个例子是的,我知道它是复杂的,但它做我想要的工作,将打印出"Test->Name",我也可以通过说$prop->value得到值。如果我想将值与另一个对象进行比较,我可以简单地这样做:

if($t->Name == "Test") { echo "It worked!!"; }

希望这不会让你太困惑,但这是一个有趣的PHP探索。

Php有一个内置函数get_class