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
🐞
🛠
🐘
🚀
5. The legend of strpos()
<?php
if (strpos($string, 'a')) { }
if (strpos($string, 'a') == 0) { }
if ($x = strpos($string, 'a')) { }
🐞
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)) { }
🐘
50. The no-name™ brand<?php
preg_match(
'/(?<here>a) # named subpattern
(b) # optional b
(.?) # because Damien told us
/', 'adc', $r);
print_r($r);
/*
Array
(
[0] => ad
[here] => a
[1] => a
[2] =>
[3] => d
)
*/
🐘
51. Do not unset() properties
<?php
class x {
public $y = 1;
}
$x = new x();
unset($x->y);
print_r($x);
?>
x Object
(
)
🐞
Undefined property: x::$y
52. Do not unset() properties
<?php
class x {
public $y = 1;
}
$x = new x();
$x->y = null;
var_dump(isset($x->y));
print_r($x);
?>
bool(false)
x Object
(
[y] =>
)
🐘
53. Do not set properties
<?php
class x {
public $y = 1;
}
$x = new x();
$x->z = 3;
print_r($x);
?>
x Object
(
[y] => 1
[z] => 3
)
🚀
70. List() into the future!
<?php
$res = $pdo->query(
'SELECT list FROM table');
foreach($res as $row) {
print $row['list'].PHP_EOL;
}
?>
🛠
🐘
71. List() pour le futur!
<?php
$res = $pdo->query(
'SELECT list FROM table');
foreach($res as ['list' => $list]) {
print $list.PHP_EOL;
}
?>
🛠
🐘
72. Top 10
Dangling reference
For with count()
Next month
array_merge in loops
strpos() fail
Shorten first
unset($x->y)
Operator precedences
Missing subpattern
real is gone
73. Do you want to try those?
🛠
🐘
Exakat
PHP Static analysis
Modernize your code
https://www.exakat.io/