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

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了