访问构造函数私有属性php

时间:2015-02-10 17:38:32

标签: php oop

我有这段代码:

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岁的欢迎丹玛丽?

2 个答案:

答案 0 :(得分:1)

因为你试图在初始化之前访问该值,所以你应该尝试这个

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 />';

 }

答案 1 :(得分:0)

因为您没有为成员设置值:

public function __construct($firstName, $lastName, $age) 
{
    $this->_firstName = $firstName;
    $this->_lastName = $lastName;
    $this->_age = $age;

    echo …
}