Can you Force Type Casting in PHP?

我们两清 提交于 2020-05-23 21:41:31

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/21716603/can-you-force-type-casting-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!