php - PHP 中可以使用类作为变量吗?

标签 php class oop magic-methods

我有一个类(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/

相关文章:

php - 将 tiff(带路径)转换为 png 并删除背景(透明)- 在 PHP 中使用 Imagemagick

php - 如何在php函数中使用表单值?

php - 标签的奇怪 HTML 忽略

Python多重继承,如果两个基类都持有相同的方法,则调用第二个基类方法

java - 类、对象和实例之间的区别

swift - 从另一个类调用选择器 - Swift 3

c++ - 是否可以阻止引用的向上转换?

Perl:确定函数的定义位置

java - 复合策略模式 - java - 这段代码有多糟糕?

php - MySQL 到较旧的 MariaDB - 性能较慢