9 January 2009


PHP 5 : Declaring class level variable : Syntax error, unexpected T_NEW on line ...

In OO PHP you cannot declare an object type variable and assign it a new instance of an object at the same time.
For example, you will get the error Syntax error, unexpected T_NEW on line if you were to use the following code

class MyClass
{
var $mychild = new ChildClass();
}

class ChildClass
{
var somevar = 'hello world';
}

The reason for this error is that when declaring a class level variable it cannot be assigned a new instance of an object. Instead you have to declare the variable and then in the constructor (or some other function) you have to assign a new object value to the variable.

So, to solve the above problem we would have to do the following:

class MyClass
{
var $mychild;
function __construct()
{
$this->mychild = new ChildClass();
}
}
class ChildClass
{
var somevar = 'hello world';
}

No comments: