- class child
- {
- private $parent;
- function __construct($parent)
- {
- $this->parent = $parent;
- }
- function getnationality()
- {
- return $this->parent->nationality;
- }
- }
- $parent = new parent('hispanic');
- $child = new child($parent);
php中是通過類來完成信息封裝的,在php中定義類的語法是:
- <?php
- class class_name // 在面向對象編程類中,習慣上類的第一個字符為大寫,并且必須符合變量的命名規則.
- {
- //函數與變量的集合
- }
- ?>
在定義類時你可以按自已的喜好的格式進行定義,但最好能保持一種標準,這樣開發起來會更有效些.
數據成員在類中使用"var"聲明來定義,在給數據成員賦值之前,它們是沒有類型的,一個數據成員可以是一個整數,一個數組,一個相關數組(associative array)或者是一個對象.
下面是一個類定義的實際例子,代碼如下:
- class student
- {
- var $str_name; //姓名
- var $str_sex; //性別
- var $int_id; //學號
- var $int_english; //英語成績
- var $int_maths; //數學成績
- }
這是一個很普通定義類的簡單例子,用于顯示學生的學習成績,類名為student,student類包涵了一個學生的基本屬性:姓名、性別、學號、英語成績和數學成績.
function我們稱之為在類中被定義的函數,在函數中訪問類成員變量時,你應該使用$this->var_name,其中var_name 指的是類中被聲明的變量,否則對一個函數來說,它只能是局部變量,我們先定義一個input()的函數,用來給實例中的對象賦以初值,代碼如下:
- function input ( $name, $sex, $id, $englis, $maths)
- {
- $this->str_name=$name;
- $this->str_sex =$sex;
- $this->int_id =$id;
- $this->int_englis=$english;
- $this->int_maths=$maths;
- }//開源代碼Vevb.com
現在我們再定義一個叫“showinfo()”的函數,用于打印學生的基本情況,代碼如下:
- function showinfo() //定義showinfo()函數
- {
- echo (“姓名:$this->str_name
- ”);
- echo (“性別:$this->str_sex
- ”);
- echo (“學號:$this->int_id
- ”);
- echo (“英語成績:$this->int_english
- ”);
- echo (“數學成績:$this->int_maths
- ”);
- }
而定義好的類則必須使用new關鍵詞來生成對象:$a_student=new student;
例如我們要為一個名為$wing的對象創建實例,并進行賦值,可以使用下面的代碼:
$wing =new student; //用new關鍵詞來生成對象
$wing ->input (“wing”,”男”,33,95,87);
分別輸入wing的姓名、性別、學號、英語成績、數學成績,其中姓名和性別是字符型變量,所以需要用雙引號,其它為數值型變量則不需要.
通過下面這段完整的源代碼,我們就可以很清楚的看到類在php是怎么被運用的,代碼如下:
- class student
- {
- var $str_name;
- var $str_sex;
- var $int_id;
- var $int_english;
- var $int_maths;
- function input ( $name, $sex, $id, $english, $maths)
- {
- $this->str_name=$name;
- $this->str_sex =$sex;
- $this->int_id =$id;
- $this->int_english=$english;
- $this->int_maths=$maths;
- }
- function showinfo()
- {
- echo (“姓名:$this->str_name
- ”);
- echo (“性別:$this->str_sex
- ”);
- echo (“學號:$this->int_id
- ”);
- echo (“英語成績:$this->int_english
- ”);
- echo (“數學成績:$this->int_maths
- ”);
- }
- }
- $wing = new student;
- $wing->input (“wing”,”男”,33,95,87);
- $paladin = new student;
- $paladin->input (“paladin”,”女”,38,58,59.5);
- $wing->showinfo();
- $paladin->showinfo();
執行結果應是這樣的:
新聞熱點
疑難解答