由 php 中的函数返回的访问数组

我正在使用一个模板引擎,它将代码插入到我想要的站点中。

我编写了一个函数来测试一些非常简单的东西:

myfunction() { return '($this->data["a"]["b"] ? true : false)'; }

问题是,$this-> data 是私有的,我不能在任何地方访问它,所以我必须使用 getData () ; 这就导致了我的问题。

$this->getData()['a']['b']

不起作用,并且先赋值也不起作用,因为它将直接在 if ()块中使用。

有什么想法吗?

55358 次浏览

You cannot use something like this :

$this->getData()['a']['b']

ie, array-access syntax is not possible directly on a function-call.

Youy have to use some temporary variable, like this :

$tmp = $this->getData();
$tmp['a']['b']    // use $tmp, now

In your case, this probably means using something like this :

function myfunction() {
$tmp = $this->getData();
return ($tmp['a']['b'] ? true : false);
}

You have to :

  • first, call your getData() method, and store its return value in a temporary varibale
  • then, use that temporary variable for your test

You don't have much choice about that, actually...

$this->data is always accessible, if it is protected. $object->data is not accessible from everywhere, so if you're returning $this in your code, and it is evaluated as such, it should be ok.

Btw, there is a bug in your code: The quotes need to be escaped.

myfunction() { return '($this->data[\'a\'][\'b\'] ? true : false)'; }

Ok... apparently there really isn't a better way, so I'm going to answer myself with a not so beautiful solution:

I created the function:

arrayGet($array, $index) { return $array[$index]; }

And used it like this:

myfunction() { return '(arrayGet(arrayGet($this, "a"), "b") ? true : false)' }

This is not pretty but works.

Since PHP 5.4 it's possible to do exactly that:

getSomeArray()[2]

Reference: https://secure.php.net/manual/en/language.types.array.php#example-62

On PHP 5.3 or earlier, you'll need to use a temporary variable.

It is possible from PHP version 5.4.

If you don't want a temporary variable for that and your PHP version is less, than 5.4, than you still can use a few built in functions to get the first or the last element:

$x     = 'first?last';
$first = array_shift(explode('?', $x));
$last  = end(explode('?', $x));
$last2 = array_pop(explode('?', $x));

Edit: !!! Please note, that in later versions( 5.4+ ) PHP will throw a notice, because end only expects variables as parameter.