我使用的是PHP 5.2.5版。 我希望能够将我自己的类与int进行比较。
abstract class A {
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function __toString()
{
return $this->value;
}
}
class B extends A { }
但我希望能够像这样使用我的课程:
$inst = new B(20);
if($inst==20) {
//...
}
我该怎么做?
答案 0 :(得分:3)
您可以在班级中使用magic __toString()方法。
class A
{
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function __toString()
{
return (string) $this->value;
}
}
$inst = new A(20);
if((string) $inst==20) {
//...
}
从技术上讲,__ toString()必须返回一个字符串而不是整数,但PHP的松散输入将使用标准的宽松类型比较规则进行比较
答案 1 :(得分:1)
它被称为运算符重载。 是的,你可以做到。但是您需要使用PECL包 (摘自下面的描述:
运算符重载:+, - ,*,/,%,<<,>>,。,|,&,^,〜,!,++, - , - + =, - =,* =,/ =,%=,<< =,>> =,。=,| =,& =,^ =,〜=, ==,!=,===,!==,<和< =运算符。
)