PHP 知识量:7 - 20 - 67
get访问器用于获取类属性的值,示例如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <?php class person { private $name; private $age = 30; private $sex = 'male'; //构造函数 function __construct($setname) { $this->name = $setname; } //获取name public function getName() { echo "$this->name<br>"; } //获取age public function getAge() { echo "$this->age<br>"; } //获取sex public function getSex() { echo "$this->sex<br>"; } } //实例化类person $bob = new person('bob'); //调用get访问器 $bob->getName(); $bob->getAge(); $bob->getSex(); ?> </body> </html>
以上代码中,实例化类person后,构建了对象$bob,通过get访问器的三次调用,分别获取了对象$bob的属性$name、$age和$sex的值。
set访问器用于设置类属性的值,示例如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <?php class person { private $name; private $age = 30; private $sex = 'male'; //构造函数 function __construct($setname) { $this->name = $setname; } //获取name public function getName() { echo "$this->name<br>"; } //获取age public function getAge() { echo "$this->age<br>"; } //获取sex public function getSex() { echo "$this->sex<br>"; } //设置name public function setName($newname){ $this->name=$newname; } //设置age public function setAge($newage){ $this->age=$newage; } //设置sex public function setSex($newsex) { $this->sex=$newsex; } } //实例化类person $bob = new person('bob'); //调用get访问器 $bob->getName(); $bob->getAge(); $bob->getSex(); //调用set访问器 $bob->setName('jeff'); $bob->setAge(28); $bob->setSex('female'); //再次调用get访问器 $bob->getName(); $bob->getAge(); $bob->getSex(); ?> </body> </html>
以上代码中,通过三次调用set访问器,重新设置了对象$bob的属性$name、$age和$sex的值,再次调用get访问器后它们的值由“bob,30,male”变为了“jeff,28,female”。
Copyright © 2017-Now pnotes.cn. All Rights Reserved.
编程学习笔记 保留所有权利
MARK:3.0.0.20240214.P35
From 2017.2.6