Home >Backend Development >PHP Tutorial >How Can I Access Array Elements Returned by a Function in PHP?
Accessing Function-Returned Arrays in PHP
Consider the scenario where you have a template engine that injects code based on your specified locations. To test for a particular condition, you've created a function:
myfunction() { return '($this->data["a"]["b"] ? true : false)'; }
However, the private nature of $this->data presents a challenge, making it inaccessible from certain contexts.
To resolve this, getData() is typically employed, but it doesn't work in this case. The following approach also fails:
$this->getData()['a']['b']
Additionally, assigning the value to a variable doesn't provide a viable solution.
Solution
PHP 5.4 and above offer a direct approach:
getSomeArray()[2]
For PHP 5.3 or earlier, a temporary variable can be used:
$temp = getSomeArray(); $temp[2]
This method allows you to access the array elements returned by the function without encountering the limitations imposed by the private nature of the array.
The above is the detailed content of How Can I Access Array Elements Returned by a Function in PHP?. For more information, please follow other related articles on the PHP Chinese website!