PHP 父类方法访问子类全部属性并统一保存到数据表
数据小陈
可以。父类方法里别再通过 __CLASS__ 取属性。用 new ReflectionClass($this)(或者先用 static::class 拿到运行时类名,再构造 ReflectionClass)按实际子类做反射;对每个非静态属性调用 setAccessible(true) 和 getValue($this),就能读子类的 private、protected 和 public 属性。父类不能用普通 $this->xxx 访问子类 private 属性,protected 也不应依赖这种隐式访问。
原因在于,__CLASS__ 写在哪个类里就返回哪个类名,在 theParent::listVars() 里它永远是 theParent,所以 get_class_vars($myClass) 只看父类。继承也不会让父类获得子类 private 成员的普通访问权限;private 只属于声明它的类。反射可以在运行时检查并读取这些非公开成员。
可复用写法如下,先收集属性,再交给保存逻辑:
<?php
class theParent
{
public function collectProperties(): array
{
$data = [];
$ref = new ReflectionClass($this);
foreach ($ref->getProperties() as $prop) {
if ($prop->isStatic()) {
continue;
}
$prop->setAccessible(true);
$name = $prop->getName();
if (!$prop->isInitialized($this)) {
$data[$name] = null;
continue;
}
$data[$name] = $prop->getValue($this);
}
return $data;
}
public function save(PDO $pdo): void
{
$data = $this->collectProperties();
$table = strtolower((new ReflectionClass($this))->getShortName());
// 真实项目应对 $table 和 $data 的键做白名单校验
$columns = array_keys($data);
$placeholders = array_map(fn ($c) => ':' . $c, $columns);
$sql = sprintf(
'INSERT INTO %s (%s) VALUES (%s)',
$table,
implode(', ', $columns),
implode(', ', $placeholders)
);
$stmt = $pdo->prepare($sql);
foreach ($data as $column => $value) {
$stmt->bindValue(':' . $column, $value);
}
$stmt->execute();
}
}
class orderRecord extends theParent
{
protected string $orderDate = '2024-01-01';
protected string $orderNumber = 'A001';
}
$ord = new orderRecord;
$ord->save($pdo);
如果只想确认属性是否能被列出来,可以这样写:
class theParent
{
public function listVars(): void
{
foreach ($this->collectProperties() as $name => $value) {
printf('%s = %s' . PHP_EOL, $name, var_export($value, true));
}
}
}
注意事项:
- 未初始化的 typed property 不能直接读,先用
ReflectionProperty::isInitialized($this)判断;示例里父类protected string $a就是未初始化状态。 setAccessible(true)在旧版本 PHP 中需要;PHP 8.1 起反射默认可以访问非公开属性,但保留它通常能兼容旧代码。- 直接把类名拼进表名、把属性名拼进列名,会有 SQL 注入和保留字风险;生产代码要用固定映射或白名单,值通过
PDO预处理绑定。 - 反射能读到
private,但会绕过封装;如果保存逻辑复杂、字段又比较稳定,显式接口或映射数组更好维护。
备注:内容仅供参考。
