今天学习了面向对象编程,我先创造一个为person的类:
<?php
class person
{
public $name = '';
public $gender = '';
private $age = 0 ;
private $height = 0;
private $weight = 0;
public function __construct($name, $gender, $age, $height, $weight)
{
$this->name = $name;
$this->gender = $gender;
$this->age = $age;
$this->height = $height;
$this->weight = $weight;
}
public function __get($name)
{
// TODO: Implement __get() method.
return $this->$name;
}
public function __set($name, $value)
{
// TODO: Implement __set() method.
if ($name == 'age'){
if (in_array($value,range(14,120))){
$this->$name = $value;
}
} elseif ($name == 'height'){
if (in_array($value,range(50,300))){
$this->$name = $value;
}
}else {
$this->$name = $value;
}
}
}这个类里面含有构造方法,查询器和设置器
然后我们用下面的PHP 代码来调用这个类:
<?php
require './class/person.php';
$hongda = new person('hongda','male',25,178,70);
echo "Hello, your name is ".$hongda->name." .<br>";
echo "Your gender is ".$hongda->gender." .<br>";
echo "Your age is ".$hongda->age.' years old.<br>';
echo "Your height is ".$hongda->height.'cm.<br>';
echo "Your weight is ".$hongda->weight.'kg.<br>';
echo '<hr>';
$hongda->age = 18;
echo "Your age is ".$hongda->age.' years old.<br>';
$hongda->height = 180;
echo "Your height is ".$hongda->height.'cm.<br>';结果如下:

以上, 我先实例化了类,然后用查询器得到了对象的每个属性的value,然后用设置器改变了对象的一些属性的值。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号