PHP面向物件----(私有屬性的訪問方法)
阿新 • • 發佈:2019-01-23
<?php
//對私有屬性的訪問方法一(系統方法)
class A
{
private $name = 'hello world';
function __set($property_name,$value)
{
$this->$property_name=$value;
}
function __get($property_name)
{
if (isset($this->$property_name))
{
return ($this->$property_name );
}
else
{
return NULL;
}
}
}
$a = new A();
$a->name='ni hao';
echo $a->name;
?>
<?php
//對私有屬性的訪問方法二(開放私有屬性的訪問的介面)
class Person{
private $age; // 私有的屬性年齡
function setAge($age) // 為外部提供一個公有設定年齡的方法
{
if ($age<0 || $age >130) // 在給屬性賦值的時候,為了避免非法值設定給屬性
return;
$this->age = $age;
}
function getAge() // 為外部提供一個公有獲取年齡的方法
{
return($this->age);
}
}
$man=new Person();
$man->setAge(100);
echo '這個人的年齡是 '.$man->getAge().'歲';
?>