dongtang4954 2010-12-10 04:52
浏览 68
已采纳

我可以在PHP类中使用函数作为变量吗?

Is it possible to create a variable which runs a function and holds its return value when it's called? Like in the example below:

class Object{
     public $var = $this->doSomething();
     function doSomething(){
          return "Something";
     }
}

$object = new Object();
echo $object->$var;

Just because I get this error:

Parse error: syntax error, unexpected T_VARIABLE in test.php on line 2

  • 写回答

1条回答 默认 最新

  • douwei9759 2010-12-10 04:55
    关注

    You must initialize it in the constructor (if the value is not some 'compile-time' constant):

    class Object {
         public $var;
    
         function __construct() {
              $this->var = $this->doSomething();
         }
    
         function doSomething() {
              return "Something";
         }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services