空数组的OO PHP类变量意外t_variable


OO PHP class variable of empty array unexpected t_variable

我想将类数组初始化为空。出于某种原因,它给了我一个错误"expected T_VARIABLE"。有人知道这个类变量/数组出了什么问题吗?这就是类的样子:

class SentenceContentContainer {
    var $strSentence; //theSentence entered
    $arrayOfWords = []; //running the code has issue with this line
    function SentenceContentContainer($strSentence)
    {
        $this->strSentence = $strSentence;
    }
    function addWordToContainer(&$wordToAdd)
    {
        ...
    }
} //SentenceContentContainer

您的变量未正确定义

class SentenceContentContainer {
    public $strSentence; //theSentence entered
    public $arrayOfWords = [] // running the code has issue with this line
    ....
}

选择publicprivate或者protected,但var不那么明确,我更喜欢其他选项,但这是您的选择。但是类变量必须具有可见性关键字。

编辑:正如@AbraCadaver在本评论中提到的那样,官方文档建议您避免使用var关键字

http://php.net/manual/en/language.oop5.visibility.php

注意:由于兼容性原因,仍然支持使用var关键字声明变量的PHP4方法(作为public关键字的同义词)。在5.1.3之前的PHP 5中,使用它会生成E_STRICT警告

您使用的代码是旧的PHP 4对象语法,所以停止使用您正在学习的任何资源,开始寻找最新的东西。

var关键字和旧式构造函数(与类同名的函数)都是过去时代的遗迹。您应该使用public关键字(假设您需要公开访问这些变量)和__construct()作为构造函数。

class SentenceContentContainer {
    public $strSentence; //theSentence entered
    public $arrayOfWords = []; //running the code has issue with this line
    function __construct($strSentence)
    {
        $this->strSentence = $strSentence;
    }
    function addWordToContainer(&$wordToAdd)
    {
        ...
    }
} //SentenceContentContainer

注意,除非你需要这样做:

$sent = new SentenceContentContainer("Test sentence");
echo $sent->strSentence;

您可能应该将变量声明为private而不是public

开始:

    <?php
        class SentenceContentContainer {
            protected $strSentence;       //theSentence entered
            protected $arrayOfWords = []; //running the code has issue with this line
            function SentenceContentContainer($strSentence)
            {
                $this->strSentence = $strSentence;
            }
            function addWordToContainer(&$wordToAdd)
            {
                //...
            }
        } //Sentence