【发布时间】:2013-01-31 22:02:44
【问题描述】:
我有一个接受A 类型参数的函数(在 PHP 5 中):
function f1(A a){...}
我还有一个数组,我从$_POST['val'] 值解码并将其发送到其他函数f2:
$array1 = json_decode(stripslashes($_POST['val']));
f2($array1);
现在我想在 f2 内的每个数组元素上调用 f1:
function f2(array $a){
foreach($a as $element){
f1($element);
}
但我得到一个错误:
Argument 1 passed to f1() must be an instance of A, instance of stdClass given
当我将if($element instanceof A) 放入f2 时,我得到FALSE,但我可以正确调用$element A 的方法。
如何“告诉”f1 类型正确?
在array1 上使用print_r(name 和sourceId 在A 中):
Array
(
[0] => Array
(
[name] => connect
[sourceId] => 12
)
)
【问题讨论】:
-
stdClass不是A。它也没有方法。你永远不会从json_decode中得到A类型的东西。您需要先从数据中构造您的A对象,然后再将它们传递给f1。
标签: php casting type-hinting