作者:Devil灬旋律 | 来源:互联网 | 2018-03-21 20:25
在访问PHP类中的成员变量或方法时,如果被引用的变量或者方法被声明成const(定义常量)或者static(声明静态),那么就必须使用操作符::,反之如果被引用的变量或者方法没有被声明成cons...
在访问PHP类中的成员变量或方法时,如果被引用的变量或者方法被声明成const(定义常量)或者static(声明静态),那么就必须使用操作符::,反之如果被引用的变量或者方法没有被声明成const或者static,那么就必须使用操作符->.
另外,如果从类的内部访问const或者static变量或者方法,那么就必须使用自引用的self,反之如果从类的内部访问不为const或者static变量或者方法,那么就必须使用自引用的$this.
$this实例代码如下:
cOntent= $content;
}
function __destruct() {
} //定义析构函数
function printContent() { //定义打印函数
echo $this->content . '
';
}
}
$test = new test_this('北京欢迎你!'); //实例化对象
$test->printContent(); //北京欢迎你!
?>
::使用方法实例代码如下:
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 . '岁' . '
';
}
}
$nostop = new test_son('女性', '22'); //实例化test_son对象
$nostop->print_info(); //执行输出函数 nostop是个女性,今年23岁
?>
使用self::$name的形式.注意的是const属性的申明格式,const PI=3.14,而不是const $PI=3.14
实例代码如下:
还要注意的一点是如果类的方法是static的,他所访问的属性也必须是static的.
在类的内部方法访问未声明为const及static的属性时,使用$this->value ='class_a';的形式.
文章地址:
转载随意^^请带上本文地址!