復制代碼 代碼如下:
<?php
classname//建立了一個名為name的類
{
private$name;//定義屬性,私有
//定義構造函數,用于初始化賦值
function __construct( $name )
{
$this->name =$name;//這里已經使用了this指針語句①
}
//析構函數
function __destruct(){}
//打印用戶名成員函數
function printname()
{
print( $this->name);//再次使用了this指針語句②,也可以使用echo輸出
}
}
$obj1 = new name("PBPHome"); //實例化對象 語句③
//執行打印
$obj1->printname(); //輸出:PBPHome
echo"<br>";//輸出:回車
//第二次實例化對象
$obj2 = new name( "PHP" );
//執行打印
$obj2->printname();//輸出:PHP
?>
復制代碼 代碼如下:
<?php
classcounter//定義一個counter的類
{
//定義屬性,包括一個靜態變量$firstCount,并賦初值0 語句①
private static $firstCount = 0;
private $lastCount;
//構造函數
function __construct()
{
$this->lastCount =++self::$firstCount;//使用self來調用靜態變量 語句②
}
//打印lastCount數值
function printLastCount()
{
print( $this->lastCount );
}
}
//實例化對象
$obj = new Counter();
$obj->printLastCount();//執行到這里的時候,程序輸出1
?>
復制代碼 代碼如下:
<?php
//建立基類Animal
class Animal
{
public $name; //基類的屬性,名字$name
//基類的構造函數,初始化賦值
public function __construct( $name )
{
$this->name = $name;
}
}
//定義派生類Person 繼承自Animal類
class Person extends Animal
{
public$personSex;//對于派生類,新定義了屬性$personSex性別、$personAge年齡
public $personAge;
//派生類的構造函數
function __construct( $personSex, $personAge )
{
parent::__construct( "PBPHome"); //使用parent調用了父類的構造函數 語句①
$this->personSex = $personSex;
$this->personAge = $personAge;
}
//派生類的成員函數,用于打印,格式:名字 is name,age is 年齡
function printPerson()
{
print( $this->name. " is ".$this->personSex. ",age is ".$this->personAge );
}
}
//實例化Person對象
$personObject = new Person( "male", "21");
//執行打印
$personObject->printPerson();//輸出結果:PBPHome is male,age is 21
?>
|
新聞熱點
疑難解答