如何更新PHP中Page对象内的Content字符串?
问题
想要更新PHP中Page对象内的Content字符串,遍历得到的Page对象结构如下:
object(Page)#1716 (20) { ["_cache_statusFlags":protected]=> NULL ["creatableChildrenCache":protected]=> NULL ["destroyed"]=> bool(false) ["record":protected]=> array(22) { ["ClassName"]=> string(4) "Page" ["ID"]=> int(1) ["ParentID"]=> int(0) ["Title"]=> string(5) "Home" ["MenuTitle"]=> NULL ["URLSegment"]=> string(4) "home" ["Content"]=> string(2210) " My content that needs to be updated "... }
尝试过json_decode、强制类型转数组,要么报Uncaught Error: Cannot use object of type Page as array,要么没报错但更新失败,尝试的代码如下:
// json_decode($results,true); foreach ($results as $result) { json_decode($result,true); // 似乎没作用 // 试过 (array)$result['record']['Content'], (array)$result['Content'],... // $result['Content'] = str_replace($keywords,'<span class="highlight-search">' .$keywords . '</span>',$result->Content); $result['record']['Content'] = str_replace($keywords,'<span class="highlight-search">' .$keywords . '</span>',$result->Content); }
也试过foreach($result as $key => $field)的方式,都是盲目尝试,求正确操作流程。
解决方案
1. 优先使用类提供的公共方法(推荐)
Page作为面向对象的类,大概率为Content属性提供了公共的读取和修改方法(比如getContent()和setContent()),直接调用这些方法是最规范的做法:
foreach ($results as $result) { // 获取原始内容 $originalContent = $result->getContent(); // 替换关键词并生成新内容 $updatedContent = str_replace($keywords, '<span class="highlight-search">' . $keywords . '</span>', $originalContent); // 设置新内容 $result->setContent($updatedContent); // 如果需要将修改持久化到数据库,调用类的保存方法(示例) // $result->save(); }
2. 无公共方法时用反射访问protected属性(不推荐)
如果Page类没有提供公共方法,可通过PHP反射机制突破protected属性的访问限制,但这种做法会破坏类的封装性,仅作为临时方案:
foreach ($results as $result) { // 初始化反射对象 $reflection = new ReflectionObject($result); // 获取protected的record属性 $recordProp = $reflection->getProperty('record'); // 允许外部访问该属性 $recordProp->setAccessible(true); // 读取record数组 $record = $recordProp->getValue($result); // 修改Content值 $record['Content'] = str_replace($keywords, '<span class="highlight-search">' . $keywords . '</span>', $record['Content']); // 将修改后的数组写回属性 $recordProp->setValue($result, $record); // 如需持久化,调用保存方法 // $result->save(); }
之前操作无效的原因
json_decode($result, true)完全无效:$result是PHP对象,不是JSON字符串,该函数仅用于解析JSON格式的字符串。- 直接用
$result['record']['Content']报错:$result是对象类型,必须用->访问属性,且record是protected属性,外部无法直接访问。
内容的提问来源于stack exchange,提问作者user805528
相关产品推荐
相关产品推荐

