0

Here is a variable and it's output is following :

$a = [2, 3, 4];  
echo implode(',', $a);

Output

2,3,4

And

I have a class with a php magic method __call

class MagicMethod {

    public function __call ( $pm, $values ) {
        echo "there is not <b>$pm</b> method <br/> and arguments are <br/>";
        echo implode(',', $values);
    }
}

$magic =  new MagicMethod;    
$magic->notExist( [2, 3, 54] );

Now it's showing me error message :

Notice: Array to string conversion in

Why is the __call method getting array data?

5
  • Because you give it an array? ( [2, 3, 54] => thats an array ). And afterwards you try to echo the array, which then results in the "Array to string conversion..." Commented Sep 30, 2016 at 13:47
  • Because you're passing a single argument, which happens to be an array; so inside __call(), it's $values[0].... use echo implode(',', $values[0]); inside your __call() method Commented Sep 30, 2016 at 13:47
  • php implode() function need array data of it's 2nd arguments and I did it !! Commented Sep 30, 2016 at 13:48
  • @Xatenev I echo the array with implode function ! Commented Sep 30, 2016 at 13:50
  • echo implode(',', $values); Commented Sep 30, 2016 at 13:52

2 Answers 2

2

Second argument of __call() is an array of all arguments that were passed to the method.

From PHP docs:

The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.

In your case $values would be:

[
    [2, 3, 54]
]

What you are doing is calling implode() on this array, which results in a Array to string conversion error because [2, 3, 54] cannot be converted to a string.

Sign up to request clarification or add additional context in comments.

Comments

0

$values in __call method is array of arguments passed in notExist method.

So array passed in notExist method will be accessed by $values[0].

See following code.

class MagicMethod {

    public function __call ( $pm, $values ) {
        echo "there is not <b>$pm</b> method <br/> and arguments are <br/>";
        echo implode(',', $values[0]);
    }
}

$magic =  new MagicMethod;    
$magic->notExist( [2, 3, 54] );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.