$this关键字和紧凑的功能

2022-08-30 21:53:52

在某些上下文中,我们可以使用语法来引用对象属性。为什么不行?有没有办法解决这个问题?array($this, 'variable')compact(array($this, 'variable'))


class someclass {

    $result = 'something';

    public function output() {
        compact($this->result); // $this is a OOP keyword and I don't know how to use it inside a compact() brackets
    }
}

我目前只找到了一个解决方案:

$result = $this->result;
compact('result');

但这是丑陋的。


答案 1

我知道这已经很老了,但是我想要一个我正在做的项目这样的东西。以为我会分享我想出的解决方案:

extract(get_object_vars($this));
return compact('result');

它的扩展性相当不错。例如:

<?php

class Thing {
    private $x, $y, $z;

    public function __construct($x, $y, $z) {
        $this->x = $x;
        $this->y = $y;
        $this->z = $z;
    }

    public function getXYZ() {
        extract(get_object_vars($this));
        return compact('x', 'y', 'z');
    }
}


$thing = new Thing(1, 2, 3);
print_r($thing->getXYZ());

请小心使用。


答案 2

简短的回答:不要使用。在这种情况下,这是毫无意义的(在大多数情况下,它是毫无意义的,但那是另一回事)。相反,只返回数组有什么问题?compact()

return array('variable' => $this->variable);