【问题标题】:PHP Variables for class wont work类的 PHP 变量不起作用
【发布时间】:2012-05-22 11:49:42
【问题描述】:

我需要 php 方面的帮助。我有一个脚本,我需要它来包含一个文件。 这是我想做的

class example{
var $firstname = file_get_contents("myfirstname.txt");
var $lastname = file_get_contents("lastname.txt");
}
?>

【问题讨论】:

  • 看起来反勾号弄乱了您的标记。
  • @Daedalus,来自 stackoverflow 标记(我在删除其他标记时错过了删除它)
  • 为什么要以这种方式实例化一个类?

标签: php php-5.3


【解决方案1】:

或者在 PHP > 5 中

class Example{
    public $firstname;
    public $lastname;

    function __construct() {
        $this->firstname = file_get_contents("myfirstname.txt");
        $this->lastname = file_get_contents("lastname.txt");
    }
}

【讨论】:

    【解决方案2】:

    您不能在类内的变量声明中使用像file_get_contents 这样的函数。您可以在构造函数中分配值:

    class Example{
        public $firstname;
        public $lastname;
    
        function Example() {
            $this->firstname = file_get_contents("myfirstname.txt");
            $this->lastname = file_get_contents("lastname.txt");
        }
    }
    

    【讨论】:

      【解决方案3】:

      你不能这样初始化类成员。

      查看手册:http://pt2.php.net/manual/en/language.oop5.properties.php

      你只能用常量值初始化类成员。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-06
        • 1970-01-01
        • 1970-01-01
        • 2013-11-10
        • 2015-09-30
        相关资源
        最近更新 更多