如何创建一个PHP类,它可以被铸造为布尔(是truthy或falsy) [英] how to create a php class which can be casted to boolean (be truthy or falsy)

查看:91
本文介绍了如何创建一个PHP类,它可以被铸造为布尔(是truthy或falsy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个集合类,并希望它是插入式更换为数组,这是我目前使用。

I am creating a collection class and would like it to be drop-in-replacement for arrays, which I use currently.

如何创建可能被铸造为Boolean类,因此类可以是truthy或falsy?

一个简单的测试表明,空类的一个对象是truthy:

A simple test shows that an object of empty class is truthy:

class boolClass {}
$obj = new boolClass();
var_dump( (bool)$obj);
//prints 
//bool(true)

但我需要来决定,如果我的类是truthy或falsy。有ENY办法告诉PHP引擎如何投我的班布尔?就像我可以做__toString()?

But I need to decide if my class is truthy or falsy. Is there eny way to tell the PHP engine how to cast my class to boolean? Like I could do with __toString()?

背景:

可以说,我写这样一个类(这是一个示例只):

Lets say I write a class like this (it's an example only):

class MyCollection implements ArrayAccess, Iterator {
    //...
}

我目前大量使用这种模式:

I heavily use this patterns currently:

$var = array();

if (empty($var)) {
   //array is empty, (or there is no array at all)
   // I do something here
}

我想这看起来像:

I would like that to look like:

$var = new MyCollection(array());

和保持休息不变。但含有MyCollection的的是$ var总是truthy所以我需要的所有条件:

and keep the rest unchanged. But the $var containing MyCollection is always truthy so I would need to all the conditions to:

if ($var->isEmpty()) {
    //...
}

但是,这是不可接受的,因为我的codeBase的有许多兆字节。

But this is unacceptable, as my codebase have many megabytes.

在这里的任何解决方案?

Any solution here?

推荐答案

在此页面中,神奇的方法,您可以为您的类枚举。

On this page, the magic methods that you can define for your classes are enumerated.

<一个href=\"http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring\">http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring

您证明你已经知道 __的toString()

不幸的是,上市有什么神奇的方法,做你的要求。所以,我觉得现在你唯一的选择是明确定义一个方法,并调用该方法。

Unfortunately, there is no magic method listed there that does what you are asking. So, I think for now your only option is to define a method and call that method explicitly.

这篇关于如何创建一个PHP类,它可以被铸造为布尔(是truthy或falsy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆