php類型之class類,對象,構造函數的理解


class Student{
//1.成員屬性
/*
* <1>public關鍵字表示聲明的變量是共用的,任何地方都能訪問到
    <2>private關鍵字表示變量是私有的,只能在同一類中訪問到
    <3>protected關鍵字表示變量是受保護的,只能在同一類和類的子類中訪問。
  */

public $name = "zhangsan",$score,$num;
//構造函數傳參
public function __construct($name,$score,$num)
{
$this->name = $name;
$this->score = $score;
$this->num = $num;
}
//析構函數
public function __destruct()
{
echo "函數死了";
// TODO: Implement __destruct() method.
}
//2.成員方法
//當前學生會唱歌
public function sing($songname){
return"會唱{$songname}歌";
}
//當前學生會跑步
public function run(){
return"學生會跑步";
}
//介紹自己
public function showSelf(){
echo "我叫{$this->name},學號是{$this->num},我考了{$this->score}分,我{$this->sing("小星星")}";
}
}

//實例化對象
$student1 = new Student("王五",95,1001);

//對象訪問成員屬性
$student1->name="lisi";


//對象訪問成員方法
$student1->sing("小星星");
$student2->showSelf();


//instanceof 用於檢測當前對象實例是否屬於某一個類的類型,返回bool值
eg:
  echo $student1 instanceof Student; // 結果是true
 
 

 

 

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM