面向物件之常量和靜態屬性
阿新 • • 發佈:2021-09-05
面向物件之常量和靜態屬性
一、類常量
定義
const PI = 3.14;
在類外部可以使用define
和const
定義常量.但在類內部只能使用const
定義常量.
定義常量名稱一般都大寫,這是一個約定.
如果定義的常量有多個單片語成,使用_
連線,這也是約定。
呼叫
class Math { const PI = 3.14; public function __construct() { echo "這是Math類。裡面定義了一個常量".self::PI; } } echo Math::PI; //類名::常量名 $m = new Math(); //self::常量名
常量前面不能加訪問修飾符
二、靜態屬性和靜態方法
如果用來關鍵字static
修飾屬性和方法之後,那麼該屬性和方法是屬於整個類的,不是屬於某個物件的
class MyObject { public static $a = 0; function MyMethod() { self::$a += 2; echo self::$a . "\n"; } } $instance1 = new MyObject(); $instance1 -> MyMethod(); $instance2 = new MyObject(); $instance2 -> MyMethod();
靜態方法注意項:
1、靜態屬性和方法前面可以加訪問修飾符
class Student
{
public $name;
public static function tell()
{
echo '我是一個靜態方法';
}
}
2、靜態方法中不能出現$this
關鍵字.this代表的是物件
class Student { public static $name; public $age; public static function tell() { echo '我是一個靜態方法'; echo self::$name;//靜態方法呼叫靜態屬性,使用self關鍵詞 echo $this->age;//此處報錯。靜態方法不能呼叫非靜態屬性 } } Student::tell();
2、物件能夠訪問靜態方法
$stu = new Student();
$stu->tell();
3、靜態屬性和靜態方法效率高
4、通過靜態 方法來建立單例物件
三、幾個操作符
$this
指標是類的當前例項,是當前物件的引用。
self::
表示的是類本身,使用 self:: 時必須在操作符後面加上 $
符號,在類之外的程式碼中不能使用這個操作符,而且它 不能識別自己在繼承樹層次結構中的位置 在擴充套件類中使用 self:: 作用域時, self 可以呼叫基類中宣告的方法,但它呼叫的總是已經在擴充套件類中重寫的方法。
class A
{
public function say()
{
echo 'xxx';
}
}
class B extends A
{
public function youSay(){
self::say();
}
}
$b = new B();
$b->youSay(); // xxx
parent::
在擴充套件類中,在基(父)類的方法被重寫的情況下,如果你要訪問基類的方法,可以使用 parent::
static::
使我們不再需要使用 self:: 和 parent:: 。當希望指向最終的實現功能的類時,就可以使用static
,這個限定符會在程式碼執行之前立即計算出繼承層次結構上最後那個類的成員。
class A
{
public static function demo()
{
echo static::test();
}
public static function test()
{
return 'test-A';
}
}
class B extends A
{
public static function test()
{
return 'test-B';
}
}
class C extends A
{
public static function test2()
{
return 'test-C';
}
}
echo C::demo();
來自為知筆記(Wiz)