I want to do something like this without using extra variables:
class className {
public static function func(){
return array('true','val2');
}
}
if(className::func()[0]) {
echo 'doğru';
} else {
echo 'Yanlış';
}
I want to do something like this without using extra variables:
class className {
public static function func(){
return array('true','val2');
}
}
if(className::func()[0]) {
echo 'doğru';
} else {
echo 'Yanlış';
}
className::func()[0]
is called array dereferencing, and is not valid syntax in all PHP versions. It will be is available starting in PHP 5.4, currently in beta, released March 2012. For earlier PHP version, you will need to use an extra variable somewhere to store the array returned from className::func()
.
See the PHP 5.4 Array documentation for implementation details.
Array Deferencing is not currently available in PHP. It is on the table for PHP 5.4.
Until then, you would need the extra variable:
$arr = className::func();
if($arr[0]){
echo 'doğru';
}else{
echo 'Yanlış';
}
Well,you can return an object in your method instead. something like:
class className{
public static function func(){
return (object)array('true'=>'true','val2'=>'val2');
}
}
echo className::func()->true;//Extra variables go away =)
As the others noted, you currently cannot do it this way. If you really cannot use an temporary variable (although I don't see a reason not to use one) you could use
if(current(className::func())) // or next() or reset()
But make sure you read the documentation about these functions to treat empty arrays properly.
Reference: current