PHP 7 – What to pay attention to?
Here are some gotchas you need to keep your eye on them while you are developing in PHP, especially if you are new to PHP 7 new features.
In this post, we are going to touch a little bit of type-hinting and reference problem.
One of the nice thing about PHP 7, is the type hinting feature, which this will help us to declare what type of arguments passed to a method(function).
Look at this tiny class Car just for an example purpose:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
class Car { private $type; private $color; private $forSale; public function __construct($type, $color){ $this->type = $type; $this->color = $color; } // We have write a type-hint here which is string in this case public function setForSale(string $forSale){ $this->forSale = $forSale; } } // So here $bmw is an instance object of class Car $bmw = new Car('BMW', 'blue'); $bmw->setForSale("true"); var_dump($bmw); // $bmw->forSale will be a type of [ string(4) "true"] // Pass a boolean instead of string $bmw->setForSale(true); var_dump($bmw); // $bmw->forSale will be a type of [ string(1) "1"] // Pass an integer instead of string $bmw->setForSale(999); var_dump($bmw);// $bmw->forSale will be a type of [ string(3) "999"] ?> |
As you see above:
If we pass a string as an argument to a method that expects a string, everything is OK.
“true” => “true”
If we pass a boolean as an argument to a method that expects a string, the boolean will be cast to “1” (“0′ if we pass false).
true => “1”, false => “0”
If we pass an integer as an argument to a method that expects a string, it will be converted to a string.
999 => “999”
Did you see the problem?
As a developer, when you work with a team, not everyone knows what you would expect from them to pass to methods you coded.
You need to write code that will not break and you want other developers to use your classes without changing the behavior of your code.
So type-hint is a good place to avoid issues and it’s clear to other developers.
But still, you want to do your best to avoid casting that will cause problems in your code, as you saw on the above example, when a casting to arguments have taken a place in the run-time of your program.