I'm trying to call an array variable directly from a method that returns it. Something like the following:
function some_meth()
{
return array('var1' => 'var);
}
I know I can do something like this:
$var = some_meth();
$var = $var['var1'];
But I would like to be able to do this in one line, something like this:
$var = some_meth()['var1'];
This returns the error below, which makes sense, but is there a way to do this in one line?
Trying to get property of non-object
In pre-php5.4 this is not possible in a single call. 5.4 on you can accomplish it just like in your example.
From http://docs.php.net/manual/en/language.types.array.php
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
<?php
function getArray() {
return array(1, 2, 3);
}
// on PHP 5.4
$secondElement = getArray()[1];
// previously
$tmp = getArray();
$secondElement = $tmp[1];
// or
list(, $secondElement) = getArray();
?>
This is possible in new 5.4 version, released 1 March
More information here