PHP has its own treasure chest of classic mistakes that surprises even the most seasoned expert : code that dies just by changing its namespace, strpos() that fails to find strings or arrays that changes without touching them.
Do that get on your nerves too ? Let’s make a list of them, so we can always teach them to the new guys, spot them during code reviews and kick them out of our code once and for all. Come on, you’re not frightening us !
3. WHO'S SPEAKING?
➤ Damien Seguy
➤ CTO at Exakat
➤ Static analysis tool
➤ Elephpant retirement home
4. A bug waiting in the code
A performance potential
A convenient tool
The way of the elephpant
Ask questions along the way in
the chat section
🐞
🛠
🐘
🚀
I stay after the show
6. The real face of strpos()
<?php
// Only for comparison with 0/false
if (strpos($string, 'a') === false) { }
// No zero, no confusion
if (strpos($string, 'a') == 2) { }
// strpos() is not the only one...
if (preg_match($regex, $string)) { }
🐘
42. I want the index
<?php
class x {
public $a = 0;
function __construct() {
$this->a = rand(0, 10);
}
}
$array = array(new x, new x, new x);
array_column($array, 'a');
🐘
Array
(
[0] => 3
[1] => 7
[2] => 5
)
43. I want the property
<?php
class x {
private $a = 0;
function __construct() { $this->a = rand(0, 10
function __get($a) { return $this->a;}
}
$array = array(new x, new x, new x);
array_column($array, 'a');
🐘
Array
(
[0] =>
[1] =>
[2] =>
)
44. I want the magic property
<?php
class x {
private $a = 0;
function __construct() { $this->a = rand(0, 10
function __get($a) { return $this->a;}
function __isset($a) { return true;}
}
$array = array(new x, new x, new x);
array_column($array, 'a');
🐘
Array
(
[0] => 3
[1] => 7
[2] => 5
)
45. I want the private property
<?php
class x {
private $a = 0;
function __construct() { $this->a = rand(0,
function foo() {
$array = array(new x, new x, new x);
print_r(array_column($array, 'a'));
}
}
(new x)->foo();
🐘
Array
(
[0] => 3
[1] => 7
[2] => 5
)
62. The no-name™ brand<?php
preg_match(
'/(?<here>a) # named subpattern
(b)? # optional b
(.?) # because Damien told us
/x', 'abc', $r);
print_r($r);
/*
Array
(
[0] => ad
[here] => a
[1] => a
[2] =>
[3] => d
)
*/
🐘