批改状态:合格
老师批语:
类的申明、实例化类、类常量、类方法的重写以及类的继承
<?php
// 类的声明与实例化
// 父类
class Demo1
{
// 类常量使用关键字: const 定义
const SITE_NAME = '教师管理系统';
public $name;
protected $salary;
private $age;
// 初始化属性
public function __construct($name, $salary)
{
$this -> name = $name;
$this -> age = $salary;
}
}
// 子类
class Demo2 extends Demo1
{
private $sex;
// 重写类常量
const SITE_NAME = '学生管理系统';
// 重写父类方法
function __construct($name, $age, $sex = 'male')
{
//引用父类的构造方法来简化代码
parent::__construct($name, $age);
$this->sex = $sex;
}
// 重载属性
public function __get($name)
{
if(isset($this -> $name)){
return $this -> $name;
}
return '无此属性!';
}
}
$dome2 =new Demo2('peter', 6000);
// 访问类属性
echo $dome2 -> name.'<br>';
echo $dome2 -> salary.'<br>';
echo $dome2 -> age.'<br>';
// 访问类常亮
echo Demo1::SITE_NAME,'<br>';
echo Demo2::SITE_NAME;点击 "运行实例" 按钮查看在线实例

类中静态成员的声明与访问
<?php
// 类中静态成员的申明与访问
class Demo {
public static $pdo;
protected static $db = [
'type' => 'mysql',
'host' => '127.0.0.1',
'dbname' => 'test',
'user' => 'root',
'pass' => ''
];
public static function connect()
{
$dsn = self::$db['type'].':host='.self::$db['host'].';dbname='.self::$db['dbname'];
self::$pdo = new PDO($dsn, self::$db['user'], self::$db['pass']);
}
public static function sect($table, $fields='*', $num=5)
{
// 预处理
$stmt = self::$pdo->prepare("SELECT {$fields} FROM {$table} LIMIT {$num}");
// 执行查询操作
$stmt -> execute();
// 返回查询结果
return $stmt -> fetchAll(PDO::FETCH_ASSOC);
}
}
// 连接数据库
Demo::connect();
// 查询表中的数据
$result = Demo::sect('user', 'name, age, salary', 6);
echo '<pre>',var_export(($result));点击 "运行实例" 按钮查看在线实例

总结:
1类属性或类方法的访问控制:public(公有),protected(受保护)或 private(私有)
2.类中非静态成员使用$this->访问,静态成员使用self::访问
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号