是否可以使用 class 作为 PHP 中的变量?
Is it possible to use class as variable in PHP?
我有一个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);
我想使用 class 作为变量,例如:
$result = $int + 10;
我不知道,我怎么能 return $int;
?
是的,参见 php 的 call_users_func() 页面的示例 4;
<?php
class myclass {
static function say_hello()
{
echo "Hello!\n";
}
}
$classname = "myclass";
call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3
$myobject = new myclass();
call_user_func(array($myobject, 'say_hello'));
?>
public function __construct($variable) {
$this->varaible = $variable;
}
是不是这种类型?在 $this->variable ?
上
PHP 不支持重载运算符(这是您正在寻找的技术问题)。当其中一个操作数是 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);
我有一个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);
我想使用 class 作为变量,例如:
$result = $int + 10;
我不知道,我怎么能 return $int;
?
是的,参见 php 的 call_users_func() 页面的示例 4;
<?php
class myclass {
static function say_hello()
{
echo "Hello!\n";
}
}
$classname = "myclass";
call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3
$myobject = new myclass();
call_user_func(array($myobject, 'say_hello'));
?>
public function __construct($variable) {
$this->varaible = $variable;
}
是不是这种类型?在 $this->variable ?
PHP 不支持重载运算符(这是您正在寻找的技术问题)。当其中一个操作数是 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);