PHP cannot automatically use function result as array (in PHP 5.3) - php

When I try to run something like
getParent($child)[0]->user
I get the following error:
PHP Parse error: syntax error, unexpected '[', expecting ')' in /.....
The problem can be avoided if I do something like this:
$get_parent = getParent($child);
$parent = $get_parent[0]->user;
Is there a better way to do in php 5.3

No, before PHP5.4, you have to do that.
Array dereferencing comes from PHP 5.4.
But if getParent return an object which implement the ArrayAccess interface, you could chain it with:
$parent = getParent($child)->offsetGet(0)->user;
If it just return an array, then a temp variable is necessary.

Actually, there is a way to achieve that without temporary variable. But I definitely wouldn't recommend to use it (because, yes, it's one-liner and it's not using temporary variable, but no - it's not readable):
function getParent($child=null)
{
//mock:
return array(
(object)(array('user'=>'foo', 'data'=>'fee')),
(object)(array('user'=>'bar', 'data'=>'bee')),
);
};
//array(null) will have 1 key, 0;
//however, to get another offset N, use array(N => null) instead
$result = array_shift(array_intersect_key(getParent('baz'), array(null)))->user;
-so use temporary variable if your version in <5.4
Where it may be helpful - is in debugger, where you're forced to use "one-liners" to check some expression(s)

There is no better way to do it when using PHP version < 5.4.
If you still want to use one line instead of 2 and you always want to get the first element, you can try the following
echo reset(getParent($child))->user;
This reset the array pointer to 0 and returns the value.

Related

PHP Variable Function Array Value

I need to use variable function names for a project I'm working on but have run into a bit of strange issue. The function name ends up as a string element in an array.
This works:
$func = $request[2];
$pages->$func();
This doesn't:
$pages->$request[2]();
And I can't figure out why. It throws an array to string conversion error, as if it's ignoring that I have supplied a key to a specific element. Is this just how it works or am I doing something wrong?
As for php 5, you can use curly-braced syntax:
$pages->{$request[2]}();
Simple enough example to reproduce:
<?php
$request = [
2 => 'test'
];
class Pages
{
function test()
{
return 1;
}
}
$pages = new Pages();
echo $pages->{$request[2]}();
Alternatively (as you noted in the question):
$methodName = $request[2];
$pages->$methodName();
Quote from php.net for php 7 case:
Indirect access to variables, properties, and methods will now be
evaluated strictly in left-to-right order, as opposed to the previous
mix of special cases.
Also there is a table for php 5 and php 7 differences for this matter just below quote in the docs I've supplied here.
Which things you should consider:
Check value of the $request[2] (is it really a string?).
Check your version of php (is it php 5+ or php 7+?).
Check manual on variable functions for your release.

PHP 5.4 to 5.3 Conversion

Are their any good resources when you are trying to get a PHP script written in a newer version to work on an older version; Specifically 5.4 to 5.3?
I have even checked out articles about the changes and I cannot seem to figure out what I am doing wrong.
Here is the error I am getting, at this moment:
Parse error: syntax error, unexpected '[' in Schedule.php on line 113
And the code it is referring to:
private static $GAMES_QUERY = array('season' => null, 'gameType' => null);
.....
public function getSeason(){
$test = array_keys(self::$GAMES_QUERY)[0]; //<<<<<<<<<< line:113
return($this->query[$test]);
}
Everything I have seen seems to say that 5.3 had self::, array_keys, and the ability to access arrays like that.
try...
$test = array_keys(self::$GAMES_QUERY);
$test = $test[0];
If I'm not mistaken, you can't use the key reference [0] in the same declaration in 5.3 like you can in 5.4 and javascript, etc.
That syntax was actually added in 5.4: http://docs.php.net/manual/en/migration54.new-features.php
So, you'll need a temporary variable to hold the result of the function, then access the index you want.
In versions lower than PHP 5.4 for the case you have you can make use of the list keywordDocs:
list($test) = array_keys(self::$GAMES_QUERY);
That works in PHP 5.4, too. But it does deal better with NULL cases than the new in PHP 5.4 array dereferencingDocs.

Need help for syntax

I'm looking for the kind to access at the value of an array directly from the object's method.
For example :
With this syntax, no problem :
$myArray = $myObject->getArray();
print_r($myArray[0])
But to reduce the number of line in source code, how to get the element directly with the method ?
I do that, but it's not correct :
$myArray = $myObject->getArray()[0];
The following is only available for PHP 5.4 and supposedly higher.
$myArray = $myObject->getArray()[0];
Unfortunately there is no quicker way below PHP 5.4.
See #deceze's answer for a good alternative.
For PHP 5.3-:
$myArray = current($myObject->getArray());
or
list($myArray) = $myObject->getArray();
If you are on php 5.4 (which support array dereferencing) you can do the second option:
$myArray = $myObject->getArray()[0];
If you are on PHP < 5.4 you can "fix" it in the class (of which the object is a instance):
class Foo
{
public function getArray()
{
return $this->theArray;
}
public function getFirstItem()
{
return $this->theArray[0];
}
}
$myObject = new Foo();
print_r($myObject->getFirstItem());
But to reduce the number of line in source code, how to get the element directly with the method ?
Although it is possible to achieve this in PHP 5.4 with the syntax you've demonstrated, I have to ask, why would you want that? There are ways of doing it in 5.3 in a one-liner, but I don't see the need to do this. The number of lines is surely less interesting than the readability of the code?
IT IS IMPOSSIBRRUUU.
Serious answer:
sadly it is not possible. You can write a very ugly wrapper like this:
function getValue($arr, $index)
{
return $arr[$index];
}
$myArray = getValue($myObject->getArray(), 0);
But that makes less readable code.
read other answers about php 5.4 Finally!

PHP Fatal Error. Does empty() try to alter the results passed into it?

Ran into a strange problem in PHP today and I'm wondering if someone can explain it. While comparing two arrays I initially tried something like this:
echo empty(array_diff( array('foo','bar') , array('bar','foo') ))
This results in the following error:
Fatal Error: Can't use function return value in write context
Rewriting this as...
$dif = array_diff( array('foo','bar') , array('bar','foo') );
echo empty($dif);
...works perfectly. Empty should just be evaluating the value passed in to it, not writing to it, so what's going wrong here? Tested in both PHP 5.2.10 and PHP 5.3.2.
I've resolved the issue by using !count() instead of empty(), but I'm curious why it doesn't work in the first place. Is empty() trying to alter the result from array_diff?
Check the manual on empty():
Note: empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).
empty(), like e.g. echo() and die(), is a language construct, and therefore has different rules than a normal function (in which your example would work fine).

Returning arrays in php causes syntax error

function get_arr() {
return array("one","two","three");
}
echo get_arr()[0];
Why does the above code throw the following error?
parse error: syntax error, unexpected '['
This is simply a limitation of PHP's syntax. You cannot index a function's return value if the function returns an array. There's nothing wrong with your function; rather this shows the homebrewed nature of PHP. Like a katamari ball it has grown features and syntax over time in a rather haphazard fashion. It was not thought out from the beginning and this syntactical limitation is evidence of that.
Similarly, even this simpler construct does not work:
// Syntax error
echo array("one", "two", "three")[0];
To workaround it you must assign the result to a variable and then index the variable:
$array = get_arr();
echo $array[0];
Oddly enough they got it right with objects. get_obj()->prop is syntactically valid and works as expected. Go figure.
You can't directly reference returned arrays like that. You have to assign it to a temporary variable.
$temp = get_arr();
echo $temp[0];
"because you can't do" that isn't a very satifying answer. But that's the case. You can't do function_which_returns_array()[$offset]; You have to store the return value in a $var and then access it.
I am pretty sure if you do :
$myArray = get_arr();
echo $myArray[0];
That it will works. You cannot use braket directly.
Indeed, you are not the only one to want such a feature enhancement: PHP Bug report #45906
you can also do
list($firstElement) = get_arr();

Categories