Question

I have a function that takes argument of type A (in PHP 5):

function f1(A a){...}

I also have an array that I decode from $_POST['val'] value and send it to some other function f2:

$array1 =  json_decode(stripslashes($_POST['val']));
f2($array1);

Now I want to call f1 on each of the array's elements inside of f2:

function f2(array $a){
    foreach($a as $element){
        f1($element);
}

But I get an error:

Argument 1 passed to f1() must be an instance of A, instance of stdClass given

When I put if($element instanceof A) inside f2 I get FALSE, but I can call on that $element the A's methods propertly.

How to 'tell' f1 that the type is right?

Using print_r on the array1 (name and sourceId are in A):

Array
(
[0] => Array
    (
        [name] => connect
        [sourceId] => 12
    )

)
Was it helpful?

Solution

Output of json_decode is an object of type stdClass so it is normal to get that error. It is not easy in PHP to cast from one object type to another but you can use this trick:

function f2(array $a){
    foreach($a as $element){
        f1 ( unserialize ( preg_replace ( "/O:\d+:\"\w+\":(.*)/", "O:1:\"A\":$1", serialize ($element) ) ) )
}

this dirty trick actually cast stdClass to object of type A.

I hope that helps.

OTHER TIPS

A second parameter to json_decode is a boolean, set it to 'true' if you want an array.

$array1 =  json_decode(stripslashes($_POST['val']), true);

Also read up on security. Blithely trusting the data you get from $_POST is a bad idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top