Typically, in a PHP application that uses the skalar variable, βtypesβ are tied to the actual string input (HTTP request). PHP has made it so simple to convert string input to numbers so you can use it to calculate, etc.
However, checking for scalar is_string values ββas suggested in your example does not make much sense. Because almost any type of variable in a scalar family is a string, or at least can be used as a string. As for the example of your class, the question will be, does it really make sense to check the type of the variable or not?
For the code you proposed, this makes no sense, because you exit the constructor with return false; . This will lead to the completion of the constructor and the return of an incorrectly initialized object.
Instead, you should throw an exception, for example. a InvalidArgumentException if the constructor argument does not provide the expected / required value type.
Leaving this aside and taking for granted that your constructor of objects should differ between a string and an integer or bool or any other type of scalar, you should do the checks.
If you do not rely on exact types of scalars, you can use a string instead.
Just make sure that the data hidden inside the object is always completely correct, and it is not possible for the incorrect data to slip into private members.
hakre
source share