访问构造函数私有专有 php
acces constructor function private propriety php
我有这个代码:
class Person {
private $_firstName;
private $_lastName;
private $_age;
public function __construct($firstName, $lastName, $age)
{
echo 'Welcome '.$this->_firstName. ' '. $this->_lastName. 'that have '.''.$this->_age.'<br />';
}
}
$obiect = new Person("dan", "Marian", 30);
为什么不显示有 30 个的 Welcome dan marian?
因为您没有为成员设置值:
public function __construct($firstName, $lastName, $age)
{
$this->_firstName = $firstName;
$this->_lastName = $lastName;
$this->_age = $age;
echo …
}
这是因为您试图在初始化之前访问该值,您应该试试这个
public function __construct($firstName, $lastName, $age)
{
$this->_firstName=$firstName;
$this->_lastName=$lastName;
$this->_age=$age;
echo 'Welcome '.$this->_firstName. ' '. $this->_lastName. 'that have '.''.$this->_age.'<br />';
}
我有这个代码:
class Person {
private $_firstName;
private $_lastName;
private $_age;
public function __construct($firstName, $lastName, $age)
{
echo 'Welcome '.$this->_firstName. ' '. $this->_lastName. 'that have '.''.$this->_age.'<br />';
}
}
$obiect = new Person("dan", "Marian", 30);
为什么不显示有 30 个的 Welcome dan marian?
因为您没有为成员设置值:
public function __construct($firstName, $lastName, $age)
{
$this->_firstName = $firstName;
$this->_lastName = $lastName;
$this->_age = $age;
echo …
}
这是因为您试图在初始化之前访问该值,您应该试试这个
public function __construct($firstName, $lastName, $age)
{
$this->_firstName=$firstName;
$this->_lastName=$lastName;
$this->_age=$age;
echo 'Welcome '.$this->_firstName. ' '. $this->_lastName. 'that have '.''.$this->_age.'<br />';
}