在PHP中可以使用类作为变量吗?
我的课程如下:在PHP中可以使用类作为变量吗?,php,class,oop,magic-methods,Php,Class,Oop,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 a
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页面的示例4
公共函数结构($variable){
$this->varaible=$variable;
}
这是不是打字错误?在$this->varaible?上,PHP不支持重载运算符(这是您正在寻找的技术问题)。当其中一个操作数是类整数
时,它不知道如何处理+
,也无法教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);
这些都是神奇的方法:。看起来不太可能。$result=$int+10
表示$int
和10
具有不兼容的数据类型以进行添加,我希望返回类(int)$this->variable中的某个位置;非常感谢deceze。我想:-(
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);