構造方法

1.方法構造

class Person

{
//成員屬性
var $name;
var $age;
var $sex;
//構造方法
function __construct($name,$age,$sex)
{
$this->name=$name;
$this->age=$age;
$this->sex=$sex;
}


function say()
{
echo "我的名字:$this->name,我年齡是:$this->age,我的年齡是:$this->sex<Br>";
}
function eat()
{

}
function run()
{

}
function work()
{

}
        function __destruct()
{
echo "$this->name.再見";
}
}
$p1=new Person("gaoyuan","25","男");
$p2=new Person("gao","250","男");
$p3=new Person("yuan","2500","女");

$p1->say();
$p2->say();

$p3->say();


2.封裝和提供可更改成員屬性接口

class Person
{
//成員屬性
private $name;
private $age;
private $sex;
private $phone;
//構造方法
function __construct($name,$age,$sex)
{
$this->name=$name;
$this->age=$age;
$this->sex=$sex;
}
//成員方法
function say()
{
echo "我的名字:$this->name,我年齡是:$this->age,我的年齡是:$this->sex<Br>";
}
//提供可以改變屬性的方法
function setAge()
{
if($age <0 || $age >150)
return;
$this->age=$age;
}
function getAge()
{
return $this->age-10;
}

private function eat()
{

}
private function run()
{

}
private function work()
{

}
        function __destruct()
{
echo "$this->name.再見";
}
}
$p1=new Person("gaoyuan","25","男");
$p2=new Person("gao","250","男");
$p3=new Person("yuan","2500","女");


$p1->getage();


$p1->say();
$p2->say();
$p3->say();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章