Need help for syntax - php

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!

Related

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

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.

"Mega" Dynamic acces to static method/property in PHP 5.3?

Having this 2 classes:
class run {
public static $where = "there";
}
class there {
public static $place_name = "A beautiful place..";
}
To get place_name I can do this:
$place = "there";
echo $place::$place_name;
But I might want to do something like this at some point..:
echo {$run::$where}::$place_name;
Obviously, the last snippet doesn't work.
Is there any way to make it do work?
If you do not want to use a variable (as you said in a comment), think twice. Variables are cool in PHP, very fast and just the needed glue to work-around its limited parser (which of it was said makes PHP quite fast). So why not use a variable here? It's easy to type and quickly done.
If you don't want the variable and as we already have found out that PHP's syntax is limited, you can at least write a one-liner with PHP 5.4+ to achieve what you're looking for:
echo (new ReflectionClass((new ReflectionClass($run))->getStaticPropertyValue('where')))->getStaticPropertyValue('place_name');
which then finally should make visible that using a variable is more comfortable:
echo (unset) $place = $run::$where, $place::$place_name;
Demo: http://eval.in/13942

explode without variables [duplicate]

This question already exists:
Closed 11 years ago.
Possible Duplicate:
Access array element from function call in php
instead of doing this:
$s=explode('.','hello.world.!');
echo $s[0]; //hello
I want to do something like this:
echo explode('.','hello.world.!')[0];
But doesn't work in PHP, how to do it? Is it possible? Thank you.
As the oneliners say, you'll have to wait for array dereferencing to be supported. A common workaround nowadays is to define a helper function for that d($array,0).
In your case you probably shouldn't be using the stupid explode in the first place. There are more appropriate string functions in PHP. If you just want the first part:
echo strtok("hello.world.!", ".");
Currently not but you could write a function for this purpose:
function arrayGetValue($array, $key = 0) {
return $array[$key];
}
echo arrayGetValue(explode('.','hello.world.!'), 0);
It's not pretty; but you can make use of the PHP Array functions to perform this action:
$input = "one,two,three";
// Extract the first element.
var_dump(current(explode(",", $input)));
// Extract an arbitrary element (index is the second argument {2}).
var_dump(current(array_slice(explode(",", $input), 2, 1)));
The use of array_slice() is pretty foul as it will allocate a second array which is wasteful.
Not at the moment, but it WILL be possible in later versions of PHP.
This will be possible in PHP 5.4, but for now you'll have to use some alternative syntax.
For example:
list($first) = explode('.','hello.world.!');
echo $first;
While it is not possible, you technically can do this to fetch the 0 element:
echo array_shift(explode('.','hello.world.!'));
This will throw a notice if error reporting E_STRICT is on.:
Strict standards: Only variables should be passed by reference
nope, not possible. PHP doesn't work like javascript.
No, this is not possible. I had similar question before, but it's not

PHP arrays and pass-by-reference

The following pattern used to be possible in PHP:
function foo($arr)
{
// modify $arr in some way
return $arr;
}
This could then be called using pass-by-value:
$arr = array(1, 2, 3);
$newarr = foo($arr);
or pass-by-reference:
$arr = array(1, 2, 3);
foo(&$arr);
but "Call-time pass-by-reference has been deprecated". Modifying the function signature:
function foo(&$arr)
will handle the pass-by-reference case, but will break the dual-purpose nature of the original function, since pass-by-value is no longer possible.
Is there any way around this?
I think this is as close as you get:
function foo(&$bar) { ... }
foo($array); // call by reference
$bar = foo($_tmp = $array); // call by value
Unfortunately it will require some changes to every call.
The dual-purpose nature was stupid, which is why the behaviour is deprecated. Modify the function signature, as you suggest.
Sadly, I don't believe there is a way around it.
Just make your function use the reference with &.
A simple workaround is to prepare a wrapper function:
function foo($arr) {
return foo_ref($arr);
}
function foo_ref(&$arr) {
...
Then depending on the current use, either invoke the normal foo() or the foo_ref() if you want the array to be modified in place.
There is also a common array(&$wrap) parameter cheat, but that doesn't seem suitable in your case. A more contemporary workaround would be this tricky trick:
// pass by value
foo($array);
// pass by reference (implicitly due to being an object)
foo($array = new ArrayObject($array));
This allows for similar reference passing to unprepared functions. Personally I would prefer keeping the E_DEPRECATED warning and the intended syntax for this purpose.

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