$this keyword and compact function $this keyword and compact function arrays arrays

$this keyword and compact function


I know this is old, but I wanted something like this for a project I'm working on. Thought I'd share the solution I came up with:

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

It scales rather nicely. For example:

<?phpclass 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());

Use with care.


Short answer: don't use compact(). In this situation, it's pointless (in most situations it's pointless, but that's another story). Instead, what's wrong with just returning an array?

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


compact() looks for the variable name in the current symbol table. $this does not exist in there. What do you expect the name of $this to be anyway?

You can do:

class Foo{    function __construct()    {        $that = $this;        $var = '2';        print_r( compact(array('that', 'var')) );    }}

Ironically, once you assigned $this to $that, $this can also be compacted with 'this' nistead of 'that'. See http://bugs.php.net/bug.php?id=52110. For performance reasons $this and super-globals are only populated when they are needed. If the aren't needed they don't exist.


EDIT after Update

Your compact($this->result); looks for 'something' defined within the local/current scope of the output() method. Since there is no such variable, the resulting array will be empty. This would work:

public function output() {    $something = 1;    print_r( compact($this->result) );}