批改状态:合格
老师批语:
本实例演示了类的创建并通过完成构造方法对类成员的访问以及通过魔术方法__get()/__set()完成对类的查询及设置
类文件:
<?php
/**
*
*/
class GirlFriend1
{
//类成员:属性、方法
//类属性:初始化必须使用标量的字面量、数组
private $name = '';
private $age = 0;
private $stature = [];
//声明构造方法:实例化是自动调用
//功能:对象初始化
public function __construct($name, $age,array $stature)
{
$this->name = $name;
$this->age = $age;
$this->stature = $stature;
}
public function getName()
{
return $this->name;
}
public function getAge()
{
return $this->age;
}
public function getStature()
{
return print_r($this->stature,true);
}
//获取器
public function __get($name)
{
return $this->$name;
}
//设置器
public function __set($name,$value)
{
$this->$name = $value;
}
}点击 "运行实例" 按钮查看在线实例
演示文件:
<?php
/**
*
*/
require './class/Girfriend1.php';
$girlfriend1 = new GirlFriend1('吴婷',22,[60,50,50]);
echo "构造方法访问结果:<br>";
echo $girlfriend1->getName();
echo "<br>";
echo $girlfriend1->getAge();
echo "<br>";
echo $girlfriend1->getStature();
echo "<hr>";
echo "魔术方法访问结果:<br>";
echo $girlfriend1->name;
echo "<br>";
echo $girlfriend1->age;
echo "<br>";
print_r($girlfriend1->stature);
echo "<hr>";
echo "使用魔术方法设置age=35";
echo "<br>";
$girlfriend1->age = 35;
echo $girlfriend1->age;点击 "运行实例" 按钮查看在线实例
<?php
/**
*
*/
require './class/Girfriend1.php';
$girlfriend1 = new GirlFriend1('吴婷',22,[60,50,50]);
echo "构造方法访问结果:<br>";
echo $girlfriend1->getName();
echo "<br>";
echo $girlfriend1->getAge();
echo "<br>";
echo $girlfriend1->getStature();
echo "<hr>";
echo "魔术方法访问结果:<br>";
echo $girlfriend1->name;
echo "<br>";
echo $girlfriend1->age;
echo "<br>";
print_r($girlfriend1->stature);
echo "<hr>";
echo "使用魔术方法设置age=35";
echo "<br>";
$girlfriend1->age = 35;
echo $girlfriend1->age;点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号