Question

I have been doing some research online and it appears that the answer to my question is no, but I realize there are times when I might miss something or search for something incorrectly. I know in languages like C++, when a variable is declared it can be declared as int or string. Is it possible to force this in PHP?

For Example:

<?php
(int)$var = 5;
?>

will be validated and not cause an error in PHP, but:

<?php
$var = 5;
?>

will cause an error because it was not cast as a type string, int, object, etc...

I know PHP is loosely typed so this may not be an option, however I would like to use it that way I ensure that I sanitize data appropriately and improve readability by letting others know exactly what is going on with the code. I am hoping there is a way to enforce this in the php.ini file or to load it in a script that will always be executed by my program.

Thank you for any help you can offer!

Was it helpful?

Solution

PHP is loosely typed and does not require you to declare a variable type when declaring a variable. You can’t change that behavior with a magic php.ini directive.

The benefit of having “loose typing” is that it allows for flexibility. It allows you to create dynamic applications without having to worry about the type of the variable – PHP makes this possible by not enforcing variable types.

However, if you must convert a variable into a particular format, just cast it:

$int   = (int) $foo;
$str   = (string) $foo;
$bool  = (bool) $foo;
$float = (float) $foo;
...

There are functions to do the same, e.g. intval(), strval(), boolval() – all of them do the same task, but a function is very useful when you want to use it as a callback to another function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top