gpt4 book ai didi

php - 如何从不完整的类(class)中获取类(class)名称?

转载 作者:行者123 更新时间:2023-12-02 05:30:24 27 4
gpt4 key购买 nike

我们有一个抛出错误的错误处理程序:__PHP_Incomplete_Class 无法转换为字符串。

错误处理程序当前执行“is_object”测试,奇怪的是,对于“不完整”对象,该测试为假。我正在尝试调整错误处理程序,但我无法在不解析重新序列化版本的情况下获取原始类名。

<?php

$o = 'O:14:"BogusTestClass":0:{}';

$c = unserialize($o);

var_dump(
array(
'subject' => $c,
'is_object' => is_object($c), // false !?!?
'get_class' => get_class($c), // __PHP_Incomplete_Class
'gettype' => gettype($c), // 'object'
'Is instance of?' => $c instanceof __PHP_Incomplete_Class, // true
'serial' => serialize($c),
)
);

// Tried:

var_dump($c->__PHP_Incomplete_Class_Name);
// Error:
// The script tried to execute a method or access a property of
// an incomplete object


$refObj = new ReflectionObject($c);
$refProp = $refObj->getProperty('__PHP_Incomplete_Class_Name');
$refProp->setAccessible(true);
var_dump($refProp->getValue($c));
// Error:
// ReflectionProperty::getValue(): The script tried to execute a
// method or access a property of an incomplete object.


// This works, but is fragile, since it depends on internal behavior
// of serialize
function getBadClassName($subject)
{
$serial = serialize($subject);
$parts = explode(':', $serial, 4);

if ('O' === $parts[0] && strlen($parts[2]) -2 == $parts[1]) {
return substr($parts[2], 1, -1);
}
return '-- Error --';
}

var_dump(getBadClassName($c));

试图从不完整的对象中获取序列化类的名称以用于错误消息。

避免解析字符串,因为我猜测当使用重新定义序列化/反序列化的扩展时,字符串解析会崩溃,例如 http://pecl.php.net/package/igbinaryhttp://pecl.php.net/package/APC/3.1.7 apc.serializer 钩子(Hook)。

最佳答案

根据建议来看

forcing access to __PHP_Incomplete_Class object properties

可以通过 foreach 和 ArrayObject 访问该属性

<?php

$array = new \ArrayObject($object);
var_dump($array['__PHP_Incomplete_Class_Name']);

关于php - 如何从不完整的类(class)中获取类(class)名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12479862/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com