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.

»

PHP protected and an assault

<?php
class Victim {
  protected
$money = 100;

  public function
__toString() {
    return (string)
$this->money;
  }
}

class
Offender extends Victim {
  function
assault(Victim $victim) {
   
$victim->money = 0;
  }
}

$victim = new Victim;
$offender = new Offender;
$offender->assault($victim);
print (string)
$victim;
?>

»

PHP function calls returning references

Let's say we have this function:

<?php
function &collector() {
  static
$c = array();
  return
$c;
}
?>

we can use this like the following (very familiar to D7 coders):
<?php
 
// Note that $x = collector(); won't work.
 
$x = &collector();
 
$x[] = 'foo';
?>

Say you wanted to have one line code:
<?php
  array_push
(&collector(), 'foo');
?>

»

PHP function calls have quite some overhead

Apparently $array === (array) $array is significantly faster than is_array($array) for very small arrays. I have posted a detailed benchmark script which seems to concur: for approximately 40-50 bytes, like an array containing 5-6 integers (I am on 64 bit) or 5-6 of 8 byte strings this tricky is definitely faster.

»
Syndicate content