7

I am having trouble calling a class method from a string in PHP. Here's a simple example. Once I get this working I'll be using a variable as the method name.

Here's how I'd be calling the method normally:

$tags_array = $this->get_tags_for_image($row["id"]);

Here's how I'm trying but getting an error:

$tags_array = call_user_func('get_images_for_tag', $row["id"]);

I must be missing the scope but I can't figure out how to call the method.

----EDIT Figured out that this calls the method but $row is undefined now I believe

$tags_array = call_user_func(array($this, 'get_images_for_tag'), $row["id"]);

Full code block:

 $images = call_user_func(array($this, 'get_images_for_tag'), $filter);
        foreach ($images as $row){

            $tags_array = call_user_func(array($this, 'get_images_for_tag'), $row["id"]);
            foreach ($tags_array as $tag_row){
                $tags_array[] =  $tag_row["tag"];
            }

            $image_array []= array (
                'url' => $this->gallery_path_url . '/'. $row["name"],
                'thumb_url' => $this->gallery_path_url . '/thumbs/' . 't_'. $row["name"],
                'id' => $row["id"],
                'description' => $row["description"],
                //'url' => $row["url"],
                'tags' => $tags_array
                );
        }

3 Answers 3

16

When you want to call a method on an object with call_user_func() you have to pass it an array with the first element as the object or class name that the method will be called on and the second element being the name of the method, e.g.:

$tags_array = call_user_func( array($this,'get_images_for_tag'), $row["id"]);
Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

$tags_array = call_user_func(array($yourClassObj, 'get_images_for_tag'), $row["id"]);

Comments

1

Use this :

call_user_method('get_images_for_tag',$this,$row["id"]);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.