Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中可以使用类作为变量吗?_Php_Class_Oop_Magic Methods - Fatal编程技术网

在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);