0

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

2 Answers 2

4

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();
?>
Sign up to request clarification or add additional context in comments.

1 Comment

hmm, okay, I guess I'll have to stick with the old school way for now, we're still on 5.3. Thanks!
1

This is possible in new 5.4 version, released 1 March

More information here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.