dougan7523 2013-05-15 13:26
浏览 39
已采纳

从属性引用中获取类名

I was wondering if you could get the class name and property name from a property reference in PHP?

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

what I'm looking for is if it is possible to create the functions getClassName and getPropertyName?

  • 写回答

3条回答 默认 最新

  • dpeqsfx5186 2013-05-17 02:43
    关注

    I have figured out the way to get this to work there is a lot of magic that goes on just to get this to work, but in my case it's worth it.

    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);
    

    this example yes I know it's complex, but it does the job how I'd want it to, will print out "Test->Name" I can also get the value by saying $prop->value. If I want to compare the value to another object I can simply do this:

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

    hope this isn't too confusing but it was a fun exploration into PHP.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来