PHP 偽變數($this->)和 作用域操作符(::) 的是使用
阿新 • • 發佈:2019-01-24
<?php
header("Content-Type: text/html; charset=utf-8");
/**
*
*/
class Test
{
public $name="李四";
public $age="20";
public function test1()
{
echo $this->name,"<br>",$this->age,"<br>";
}
public function test2()
{
echo $name,"<br>",$age,"<br>";
}
}
$stud=new Test();
$stud->test1();
$stud->test2();
?>
<?php
header("Content-Type: text/html; charset=utf-8");
/**
*
*/
class Book
{
private $name ="computer";
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name=$name;
}
}
/**
*
*/
class LBook extends Book
{
}
$lbook=new LBook();
$lbook->setName("this is the book");
echo $lbook->getName();
?>
從生活中的角度來理解$this
女媧造人時, 造了一個"悔恨"的方法
{
抓[自己]頭髮
抽 [自己] 臉
}
世界上的人那麼多,
悔恨時,抓誰的頭髮?
抽誰的臉?
張三,李四? 王五? 都不能說明合理的情況
只能理解為"自己"
範圍解析操作符(也可稱作 Paamayim Nekudotayim)或者更簡單地說是一對冒號,可以用於訪問靜態成員,類常量,還可以用於覆蓋類中的屬性和方法。
當在類定義之外引用到這些專案時,要使用類名。
自 PHP 5.3.0 起,可以通過變數來引用類,該變數的值不能是關鍵字(如 self,parent 和 static)。 把 Paamayim Nekudotayim 選作雙冒號操作符的名字似乎有些奇怪。然而,這是 Zend 開發小組在寫 Zend Engine 0.5(被用於 PHP 3 中)時所作出的決定。事實上這個詞在希伯萊文就是雙冒號的意思。
<?php
header("Content-Type: text/html; charset=utf-8");
/**
*
*/
class Test{
const bookName = 'computer';
function __construct(){
echo "THE BOOK NAME IS:".Test::bookName."<br>";
}
}
/**
*
*/
class Test2 extends Test{
const bookName = 'Quantum physics';
function __construct(){
parent::__construct();
echo "THE BOOK NAME IS:".self::bookName."<br>";
}
}
$obj = new Test2();
?>