PHP 8.6把嵌套对象或数组映射成固定导出字段时,可以使用Symfony PropertyAccess读取预先定义的属性路径。导出列名与路径由服务端白名单确定,缺失路径显式报错,避免把外部输入当成任意对象访问表达式。
定义固定导出列而非开放任意路径
执行composer require symfony/property-access:^8.1。对象通过公开属性或getter读取,数组使用[键]语法,混合结构要明确两者边界。以下导出仅包含名称、城市和订单号,不把整个对象序列化。

数组字段使用方括号路径读取
严格读取允许的路径
<?php
require __DIR__.'/vendor/autoload.php';
use Symfony\Component\PropertyAccess\PropertyAccess;
final class Customer {
public function __construct(private string $name){}
public function getName():string{return $this->name;}
}
$record=['customer'=>new Customer('Lin'),'address'=>['city'=>'Hangzhou'],'order'=>['number'=>'A100']];
$columns=['customer_name'=>'[customer].name','city'=>'[address][city]','order_number'=>'[order][number]'];
$accessor=PropertyAccess::createPropertyAccessorBuilder()
->enableExceptionOnInvalidIndex()->getPropertyAccessor();
$output=[];
foreach($columns as $column=>$path){
if(!$accessor->isReadable($record,$path)){throw new RuntimeException('Missing export field: '.$column);}
$value=$accessor->getValue($record,$path);
if(!is_scalar($value)&&$value!==null){throw new RuntimeException('Non-scalar export field');}
$output[$column]=$value;
}
echo json_encode($output,JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);
对象字段通过公开属性或getter读取
可空字段和getter副作用要单独约定
默认数组缺失索引可能得到null;开启enableExceptionOnInvalidIndex后更容易区分“字段不存在”和“字段值为空”。真正允许缺失的字段可在已审核路径中使用可空语法,或者在映射层明确默认值,不对所有异常统一返回空字符串。
getValue可能调用getter,因此只使用可信数据对象和允许的字段;不要打开不需要的magic __call能力。导出前仍检查用户对记录的访问权限,PropertyAccess只是字段访问组件,不是权限系统。

缺失路径与严格异常行为



















