问题描述
我正在创建一个集合类,并希望它可以直接替换我目前使用的数组.
I am creating a collection class and would like it to be drop-in-replacement for arrays, which I use currently.
如何创建一个可以转换为布尔值的类,以便该类可以为真或假?
一个简单的测试表明一个空类的对象是真的:
A simple test shows that an object of empty class is truthy:
class boolClass {}
$obj = new boolClass();
var_dump( (bool)$obj);
//prints
//bool(true)
但我需要确定我的课程是真还是假.有没有办法告诉 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
}
我希望它看起来像:
$var = new MyCollection(array());
并保持其余不变.但是包含 MyCollection 的 $var 始终是真实的,所以我需要满足所有条件:
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()) {
//...
}
但这是不可接受的,因为我的代码库有很多兆字节.
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.
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 类(真实或虚假)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!