PHP中::、->、self、$this操作符
在访问PHP类中的成员变量或方法时,如果被引用的变量或者方法被声明成const(定义常量)或者static(声明静态),那么就必须使用操作符::,反之如果被引用的变量或者方法没有被声明成const或者static,那么就必须使用操作符->.
另外,如果从类的内部访问const或者static变量或者方法,那么就必须使用自引用的self,反之如果从类的内部访问不为const或者static变量或者方法,那么就必须使用自引用的$this.
$this实例代码如下:
<?php
// this是指向当前对象的指针
class test_this {
private $content; //定义变量
function __construct($content) { //定义构造函数
$this->content = $content;
}
function __destruct() {
} //定义析构函数
function printContent() { //定义打印函数
echo $this->content . '<br />';
}
}
$test = new test_this('北京欢迎你!'); //实例化对象
$test->printContent(); //北京欢迎你!
?>::使用方法实例代码如下:
<?php
//parent是指向父类的指针
class test_parent { //基类
public $name; //定义姓名 父类成员需要定义为public,才能够在继承类中直接使用 this来调用.
function __construct($name) {
$this->name = $name;
}
}
class test_son extends test_parent { //派生类 继承test_parent
public $gender; //定义性别
public $age; //定义年龄
function __construct($gender, $age) { //继承类的构造函数
parent::__construct('nostop'); //使用parent调用父类的构造函数,来进行对父类的实例化
$this->gender = $gender;
$this->age = $age;
}
function __destruct() {
}
function print_info() {
echo $this->name . '是个' . $this->gender . ',今年' . $this->age . '岁' . '<br />';
}
}
$nostop = new test_son('女性', '22'); //实例化test_son对象
$nostop->print_info(); //执行输出函数 nostop是个女性,今年23岁
?>使用self::$name的形式.注意的是const属性的申明格式,const PI=3.14,而不是const $PI=3.14
实例代码如下:
<?php
class clss_a {
private static $name = "static class_a";
const PI = 3.14;
public $value;
public static function getName() {
return self::$name;
}
//这种写法有误,静态方法不能访问非静态属性
public static function getName2() {
return self::$value;
}
public function getPI() {
return self::PI;
}
}
?>还要注意的一点是如果类的方法是static的,他所访问的属性也必须是static的.
在类的内部方法访问未声明为const及static的属性时,使用$this->value ='class_a';的形式.
文章地址:http://www.phprm.com/develop/fs2020.html
转载随意^^请带上本文地址!