立诚勿怠,格物致知
It's all about connecting the dots

Implicit and Explicit Casting

PHP is a loosely typed language that allows you to declare a variable and its type simply by using it. It also automatically converts values from one type to another whenever required. This is called implicit casting.
However, there may be times when PHP’s implicit casting is not what you want. In Example 4-37, note that the imputs to the division are integers. By default, PHP converts the output to floating-point so it can give the most precise value – 4.66 recurring.
Example 4-37. This expression returns a floating-point number



But what if we had wanted $c to be an integer instead? There are various ways in which this could be achived. One way is to force the result of $a /$b to be an integer value using the integer cast type (int), like this:


$c = (int) ($a / $b);

This is called explicit casting. Note that in order to ensure that the value of the entire expression is cast to an integer, the expression is placed within parentheses. Otherwise, only the variable $a would have been cast to an integer – a pointless exercise, as the division by $ b would still have returned a floating-point number.
You can explicitly cast to the types shown in Table 4-6, but you can usually avoid having to use a cast by calling one of PHP’s built-in functions. For example, to obtain an integer value, you could use the intval (获取变量的整数值,转为整数) function. As with some othersections in this book, this one is mainly here to help you understand third-party code that you may encounter.
Table 4-6. PHP’s cast types

Cast type Description
(int) (integer) Cast to an integer by dropping the decimal portion
(bool) (boolean) Cast to a Boolean
(float) (double) (real) Cast to a floating-point number
(string) Cast to a string
(array) Cast to an array
(object) Cast to an object
赞(0) 打赏
版权声明:非商业用途转载请注明文章链接,商业用途转载请联系邮箱获取授权。
文章名称:《Implicit and Explicit Casting》
文章链接:https://www.orzzone.com/implicit-and-explicit-casting.html
商业联系:yakima.public@gmail.com
本站内容仅供个人学习交流,不做为任何投资、建议的参考依据,因此产生的问题需自行承担。

评论 抢沙发

大前端WordPress主题 更专业 更方便

支持快讯、专题、百度收录推送、人机验证、多级分类筛选器,适用于垂直站点、科技博客、个人站,扁平化设计、简洁白色、超多功能配置、会员中心、直达链接、文章图片弹窗、自动缩略图等...

去看看

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力提供更多优质内容!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册