类的 PHP 变量不起作用


PHP Variables for class wont work

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

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

不能在类内的变量声明上使用像 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");
    }
}

或者在 PHP 中> 5

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

不能以这种方式初始化类成员。

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

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