我有一个类(class)如下:
class Integer {
private $variable;
public function __construct($variable) {
$this->varaible = $variable;
}
// Works with string only
public function __isString() {
return $this->variable;
}
// Works only, If Im using the class as a function (i must use parenthesis)
public function __invoke() {
return $this->variable;
}
}
$int = new Integer($variable);
我想像使用变量一样使用类:
$result = $int + 10;
我不知道,如何返回$int;
?
最佳答案
PHP 不支持重载运算符(这是您正在寻找的技术内容)。当操作数之一是类 Integer 时,它不知道如何处理 +
,并且无法指导 PHP 做什么。您能做的最好的事情就是实现适当的方法:
class Integer {
..
public function add(Integer $int) {
return new Integer($this->variable + $int->variable);
}
}
$a = new Integer(1);
$b = new Integer(2);
echo $a->add($b);
关于php - PHP 中可以使用类作为变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30703439/