是否可以在PHP中使用class作为变量?

ste*_*ull 2 php oop class magic-methods

我有一个课程如下:

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);
Run Code Online (Sandbox Code Playgroud)

我喜欢和变量一样使用类:

$result = $int + 10;

我不知道,我怎么能回来$int;

dec*_*eze 6

PHP不支持重载运算符(这是您正在寻找的技术问题).+当其中一个操作数是a时class 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);
Run Code Online (Sandbox Code Playgroud)