Call php class method from string with parameter

I am unable to call a class method from a string in PHP. Here is a simple example. As soon as I get this working, I will use the variable as the name of the method.

This is how I usually call a method:

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

This is how I try, but I get an error:

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

I need to skip the scope, but I cannot figure out how to call the method.

---- EDIT It turned out that this calls the method, but $ row undefined now I believe

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

Full block of code:

  $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 ); } 
+6
source share
3 answers

If you want to call a method on an object with call_user_func (), you need to pass it an array with the first element as the name of the object or class that the method will be called, and the second element is the name of the method, for example:

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

Try the following:

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

Use this:

call_user_method ('get_images_for_tag', $ this, $ string ["ID"]);

+1
source

Source: https://habr.com/ru/post/891702/


All Articles