decomplexity
decomplexity

Reputation: 371

Why when passing a method as argument to another method do I get 'Function name must be a string'

In the following trivial example, I am simply assigning the arguments of array $x one after the other to method Cmeth. The crashing statement should be doing something like Aobject->Cmeth("ABC") but something is hosed somewhere!

<?php

class A
{
    public function Cmeth($z)
    {
        // do something
    }
}

class B
{
    public function Dmeth(array $w, array $x)
    {
        foreach ($x as $y) {
            $w[0]->$w[1]($y); // crashes with "Function name must be a string"
        }
    }
}

$Bobj = new B;
$u = ["ABC", "DEF"];
$w = [new A, "Cmeth"];

$Bobj->Dmeth($w, $u);

Upvotes: 1

Views: 33

Answers (1)

Nick
Nick

Reputation: 147166

You need to enclose $w[1] in {} to correctly parse the expression:

$w[0]->{$w[1]}($y);

Otherwise it gets interpreted as

($w[0]->$w)[1]($y)

which is why it thinks your function name is an array, not a string.

Demo on 3v4l.org

Upvotes: 1

Related Questions