douqie3391 2014-10-21 10:13
浏览 72

括号是什么意思?

class Util_Model
{
/**
 * Get model property by property name chain.
 * Usage: Util_Model::get_prop($order, 'item', 'name')
 */
public static function get_prop()
{
    $obj  = func_get_arg(0);
    $props = array_slice(func_get_args(), 1);

    if (!is_object($obj)) {
        throw new \InvalidArgumentException('First parameter must be an object');
    }

    foreach ($props as $prop) {
        if (preg_match('/^(.*)\(\)$/', $prop, $matches)) {
            $obj = call_user_func(array($obj, $matches[1]));
        } else {
            $obj = $obj->{$prop};
        }
        if (!is_object($obj)) {
            break;
        }
    }

    return is_object($obj) ? (string)$obj : $obj;
}
}

$obj->{$prop} i wonder the meaning of this line, why there is a brace here? and why there is no error when {$prop} is null.if you don't understand my question, leave something I will amend it.thanks!

  • 写回答

2条回答 默认 最新

  • douguyi3903 2014-10-21 10:19
    关注

    $obj->{$prop} means that $obj is trying to access a property whose name is present in the variable $prop. I'll explain with an example

    class A {
         public $d;
         public $e;
         public $f;
         function X() {}
         function Y() {}
         function Z() {}
    }
    
    $obj = new A();
    $prop = 'X';
    $propVar = 'f';
    $obj->{$prop}();
    $obj->{$propVar};
    

    In the above code, $prop contains the value 'X', so function X will be invoked, likewise if it was containing values 'Y' or 'Z', they would be invoked. So the invocation of function can be decided at runtime depending on the value the variable contains.

    As for the case when $prop is null, no object is being accessed, so the reference of object is returned instead and no error is thrown.

    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站