Variable function calls

<?php
$callable
= array($x, $y);
call_user_func($callable);
$callable();
?>

call_user_func works. However, $callable() does not. Even on PHP 5.4 and later when the two supposed to be identical. How can that can be?

»

Objects with __toString are not strings.

<?php
class foo {
  function
__toString() {
    return
"x";
  }
}
$foo = new foo;
var_dump(strpos($foo, "x"));
var_dump(strpos("x", $foo));
$array = array("x" => "y");
var_dump($array[$foo]);
var_dump($foo[0]);
?>

What's the output?

»

list() is behaving logical and weird at the same time

<?php
list($a, $b) = array(1, 2, 3, 4);
?>

What direction will list start processing the array? You'd expect that it'd be left to right and that's right: $a = 1, $b = 2. But where it gets confusing:

<?php
list($a, $a) = array(1, 2, 3, 4);
?>

Well, we already know list will only consider 1 and 2. So first 1 gets assigned to $a and then 2 gets assigned and that's where our story ends, right? After all, the second $a is where $b used to be, right? Wrong. The manual warns you

»

Default arguments and type hinting

Run these three:

php -r 'function a(array $a){}; a(NULL);'
php -r 'function a(array $a = NULL){}; a(NULL);'
php -r 'function a(array $a = FALSE){}; a(FALSE);'

»

The poor parser is easily confused

PHP can just cast numbers to strings, right?

<?php
print "a"."2";
?>

<?php
print "a".2;
?>

Results
a2

PHP Parse error:  syntax error, unexpected '.2' (T_DNUMBER) in Command line code on line 1

instanceof is smart

<?php
$a
="foo";
var_dump($a instanceof stdClass);
var_dump("foo" instanceof stdClass);
?>

»

NULL is a data type and is not a scalar

While NULL is listed as a data type the consequences of this is not triivial. Most importantly, this is the reason why it is not considered a scalar. is_scalar($variable) is a shorthand for is_bool($variable) || is_string($variable) || is_int($variable) || is_float($variable) and NULL is none of those. It "feels" like NULL should be a scalar -- Wikipedia says "In computing, a scalar is any non-composite value".

»

ArrayAccess or what's the difference between NULL and nothing

So if you have class foo implements ArrayAccess, implement offsetSet simply as $this->context[$offset] = $value; then doing $x = new Foo; $x[]  = 1; results in context set to array('' => 1). You need to write this out:

<?php
if (isset($offset)) {
 
$this->context[$offset] = $value;
}
else {
 
$this->context[] = $value;
}
?>

You can try simply:
var_dump(array(NULL => 1));
array(1) {
  '' =>
  int(1)
}

»

in_array really loves typecast

<?php
$a
= array('7.1');
var_dump(in_array('7.10', $a));
?>

bool(true)
I have no explanation. Both are strings. Really: WTF?

»

More on array references

<?php
function test(&$a) {}
test($x['foo']);
?>

Don't ask me, ever, why this doesn't throw a notice or two. It creates the $x array with a foo key assigned to NULL.

»
Syndicate content