douduiwei2831
2015-06-08 07:32
浏览 135
已采纳

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

I have a class as follows:

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

I would like work with class as with variable like:

$result = $int + 10;

I don´t known, how can I return $int; ?

图片转代码服务由CSDN问答提供 功能建议

我有一个类如下:

  class Integer {  
 
private $ variable; 
 
公共函数__construct($ variable){
 $ this-> varaible = $ variable; 
} 
 
 //仅适用于字符串
public function __isString(){  
返回$ this->变量; 
} 
 
 //仅适用于工作,如果我使用类作为函数(我必须使用括号)
公共函数__invoke(){
返回$ this-&gt  ;变量; 
} 
 
} 
 
 
 $ int = new整数($ variable); 
   
 
 

我想要上课 和变量一样:

$ result = $ int + 10;

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongyun9120 2015-06-08 07:56
    已采纳

    PHP does not support overloading operators (which is the technical thing you're looking for). It doesn't know what to do with + when one of the operands is a class Integer, and there's no way to teach PHP what to do. The best you can do is implement appropriate methods:

    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);
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongqu5650 2015-06-08 07:51

    Yes, see Example 4 of php's call_users_func() page;

    <?php
    
    class myclass {
        static function say_hello()
        {
            echo "Hello!
    ";
        }
    }
    
    $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'));
    
    ?>
    
    评论
    解决 无用
    打赏 举报
  • dsj1961061 2015-06-08 07:53

    public function __construct($variable) { $this->varaible = $variable; } are this typo or not? on $this->varaible ?

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题