This question already has an answer here:
I wanted to initialize a class array as empty. For some reason, it's giving me the error "unexpected T_VARIABLE." Does anyone have an idea what's wrong with this class variable/array? This is what the class looks like:
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
</div>
The code you're using is old PHP 4 syntax for objects, so stop using whatever resource you're learning from and start looking for something recent.
The var
keyword and old-style constructors (function with same name as class) are both relics of a bygone age. You should be using the public
keyword — assuming you need to access these variables publicly — and __construct()
as a constructor function.
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
Note that unless you need to do something like this:
$sent = new SentenceContentContainer("Test sentence");
echo $sent->strSentence;
You should probably declare the variables as private
instead of public
.
Your variable is not defined correctly
class SentenceContentContainer {
public $strSentence; //theSentence entered
public $arrayOfWords = [] // running the code has issue with this line
....
}
choose public or private or protected, but var is less explicit, i prefer the others but its your choices. But your class variables must have a visibility keyword.
EDIT: as @AbraCadaver mention in this comment, the official documentation advise you to avoid var keyword
http://php.net/manual/en/language.oop5.visibility.php
Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning
Here you go:
<?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