dongyan5641 2012-08-23 12:14
浏览 24

从调用属性的位置获取变量

For some user-level debugging I would like to know from which variable a certain property from a class was called. All classes are stdClass, so I can't look for an answer in that direction.

Let's say I have a class Person with properties Name and Sex. The setup looks like $oPerson = new Person(). When I call $oPerson->FirstName = 'Jack'; I would like to figure out the call was made from $oPerson. Can this be achieved?

  • 写回答

1条回答 默认 最新

  • dongzhuang6247 2012-08-23 13:43
    关注

    This isn't perfect (see here for my inspiration and why it's not), but it's a start:

    class Person {
        var $name;
        var $sex;
    
        function Person() {
            $this->name = "Jon";
            $this->sex = "male";
        }
    
        function __get($name) {
            $var_name = "";
            foreach ($GLOBALS as $key => $val) {
                if ($val === $this) {
                    $var_name = $key;
                    break;
                }
            }
    
            echo "Getting undefined '$name' from '\$$var_name'.
    ";
    
            $trace = debug_backtrace();
            trigger_error(
                'Undefined property via __get(): ' . $name .
                ' in ' . $trace[0]['file'] .
                ' on line ' . $trace[0]['line'],
                E_USER_NOTICE);
    
            return null;
        }
    }
    
    $oPerson = new Person();
    $name = $oPerson->name;
    $fullname = $oPerson->fullname;
    

    For example, the following won't work:

    class Nerd {
        var $person;
    
        function Nerd() {
            $person = new Person();
            $nerd_fullname = $person->fullname;
        }
    }
    

    because the $person property of Nerd is not global, so it doesn't appear in $GLOBALS, nor is it within the scope of Persons's magic function __get().

    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口