将对象评估为布尔值

编程入门 行业动态 更新时间:2024-10-26 22:24:35
本文介绍了将对象评估为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请考虑以下内容:

class MyClass { private $var1 = "apple"; private $var2 = "orange"; } $obj = new MyClass(); if($obj) { // do this } else { // do that }

PHP将我的对象评估为true,因为它有成员变量。这个逻辑可以以某种方式被覆盖吗?换句话说,我可以控制我们类的对象在处理为布尔值时将要计算的对象。

PHP evaluates my object to true because it has member variables. Can this logic be overridden somehow? In other words, can I have control over what an object of my class will evaluate to when treated as a boolean?

推荐答案

PHP将我的对象评估为true,因为它有成员变量。

PHP evaluates my object to true because it has member variables.

这是不正确的。 PHP实际上评估 $ obj 为 true ,因为它包含一个对象。它与对象的内容无关。您可以通过从类定义中删除成员来验证这一点,但它不会对选择if / else的哪个分支产生任何影响。

This is incorrect. PHP actually evaluates $obj as true because it holds an object. It has nothing to do with the contents of the object. You can verify this by removing the members from your class definition, it won't make any difference in which branch of the if/else is chosen.

使PHP将一个变量评估为true,如果它持有一个对象。您必须先将以下之一分配给变量:

There is no way of making PHP evaluate a variable to true if it holds to an object. You'd have to assign one of the following to the variable first:

null array() "" false 0

更多推荐

将对象评估为布尔值

本文发布于:2023-11-05 15:46:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561239.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   布尔值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!