构造方法
2.查询器:__get()
3.设置器:__set()
并创建一个php脚本进行正确的调用
1.构造方法__construct
//构造方法也叫构造器:对象的初始化
public function __construct($name, $age, array $stature)
{
$this->name = $name;
$this->age = $age;
$this->stature = $stature;
}
2.查询器:__get()
/查询器:__get($name)
//双下划线开始的叫:魔术方法,由系统直接调用
//当访问一个没有权限读取的属性的时候,会自动调用魔术方法。可以对其进行过滤限制
public function __get($name) {
return $this->$name;
}
3.设置器__sert()
//设置器: __set($name,$value)
public function __set($name, $value){
if($name == 'age'){
//年龄:14-120之间
if(in_array($value, range(14,120))){
$this->$name = $value;
}
}else{
$this->$name = $value;
}
<?php
require './class/GirlFriend3.php';
$girlfriend3 = new GirlFriend3('冰冰姐','26',[87,98,89]);
echo $girlfriend3->name;
$girlfriend3->age = 80;
echo '<br>';
echo $girlfriend3->age;点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号