dongna1593 2012-10-09 14:43
浏览 47
已采纳

使用PHP在类中声明变量

Fairly new to classes in PHP, so bear with me.

class processRoutes
    {   
        //Next line works
        private $doc = "works as as string";
        //Next line does not work, "Parse error: syntax error, unexpected T_NEW"
        private $doc = new SimpleXMLElement('routingConfig.xml', null, true);
        private function getTablenames()
        {
            //do stuff  
        }
    }

I'm trying to ultimately utilize the SimpleXMLElement object within my class, among several private functions. What is the correct method for going about this, and why doesn't my current method work?

  • 写回答

3条回答 默认 最新

  • dongzhi4690 2012-10-09 14:46
    关注

    You need to do this in your constructor, as this can't be evaluated at this stage of script parsing. 'Simple' values, as strings, bools and numeric values will work though.

    class processRoutes
    {   
      //Next line works
      private $doc = "works as as string";
    
      private $doc;
    
      public function __construct()
      {
         $this->doc = new SimpleXMLElement('routingConfig.xml', null, true);
      }
    
      // ....
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件