5

This is probably a simple question, and I'm afraid the answer might be "no", but...

Here's a simple piece of code:

function func1() {
  $bt = debug_backtrace();
  print "Previous function was " . $bt[1]['function'] . "\n";
}

Now... Can this be done without the temporary variable? In another language, I might expect to be able to say:

function func1() {
  print "Previous function was " . (debug_backtrace())[1]['function'] . "\n";
}

Alas, in PHP, this results in an error:

PHP Parse error:  syntax error, unexpected '[' ...

If it can't be done, it can't be done, and I'll use a temporary variable, but I'd rather not.

2 Answers 2

6

No, direct dereferencing is unfortunately not supported in current versions of PHP, but will apparently come in PHP 5.4.

Also see Terminology question on "dereferencing"?.

Sign up to request clarification or add additional context in comments.

Comments

1

Array dereferencing is not available in PHP 5.3 right now, but it will be available in PHP 5.4 (PHP 5.4.0 RC2 is currently available for you to tinker with). In the meantime, you can use end(), reset(), or a helper function to get what you want.

$a = array('a','b','c');
echo reset($a);          // echoes 'a'
echo end($a);            // echoes 'c'
echo dereference($a, 1); // echoes 'b'

function dereference($arr, $key) {
    if(array_key_exists($key, $arr)) {
        return $array[$key];
    } else {
        trigger_error('Undefined index: '.$key); // This would be the standard
        return null;
    }
}

Note that end() and current() will reset the array's internal pointer, so be careful.

For your convenience, if you'll be chaining your dereferences this might come in handy:

function chained_dereference($arr, $keys) {
    foreach($keys as $key) {
        $arr = dereference($arr, $key);
    }

    return $arr;
}

// chained_dereference(debug_backtrace(), array(1, 'function')) = debug_backtrace()[1]['function']

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.