In some contexts, we can use an array($this, 'variable')
syntax, to refer to object properties. Why doesn't compact(array($this, 'variable'))
work? Is there a way to work around this?
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
}
}
I have found only one solution at the moment:
$result = $this->result;
compact('result');
But this is ugly.
The compact() function creates an array from variables and their values. Note: Any strings that does not match variable names will be skipped.
PHP | compact() Function The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values.
The compact() function is used to convert given variable to to array in which the key of the array will be the name of the variable and the value of the array will be the value of the variable.
The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.
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:
<?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());
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With