Reputation: 91
I seen some of the answers of the same questions in the forum.. but still the answers are not providing a clear idea..
In other languages like C# is executing fine. but why not PHP?
Check the example:
class Student
{
public $name;
public $age;
private $number;
}
class ss
{
public $obj;
public $objs=new Student(); //generating error
public function act()
{
$obj = new Student();
$obj->study();
$obj->studentinfo();
}
}
$ob = new ss();
$ob->act();
Upvotes: 1
Views: 687
Reputation: 4539
Try this code
class Student
{
public $name;
public $age;
private $number;
}
class ss
{
var $obj;
public function __construct()
{
$this->obj = new Student();
$this->obj->study();
$this->obj->studentinfo();
}
}
$ob=new ss();
$ob->act();
Upvotes: 1
Reputation: 4933
As per the PHP docs, any property values must be of a constant value.
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
If you want $objs
to be a new instance of Student
, you should initailise it in your constructor:
public function __constructor()
{
$this->objs = new Student();
}
Upvotes: 1