php call user method

call_user_method

call_user_method — Вызывает метод указанного объекта

Эта функция объявлена УСТАРЕВШЕЙ в PHP 4.1.0, и УДАЛЕНА в PHP 7.0.0.

Есть следующие альтернативы:

Описание

Список параметров

Имя вызываемого метода.

Примеры

Пример #1 Альтернатива call_user_method()

Смотрите также

User Contributed Notes 6 notes

class Habib <
static public function test () <
print «Hello Hasina!
» ;
>

class Habib <
static public function test () <
print «Hello Hasina!
» ;
>

This function is very similar to this:

It does not work to use Pointers as Arguments:

You can pass a variable number of parameters to a function, use a definition like:

and then you can pass 2, 3 or 4 parameters. This is explained in the «Functions» section of the manual.

See also the PHP4 functions: func_num_args(), func_get_arg(), and func_get_args(), and examples therein

From what i’ve observed, call_user_func() does everything this funciton does and a little more. I made a pretty good example call_user_func()’s usage with object instances and figured it might be useful here:

This is a demonstration of 2 neat features of PHP

* passing array arguments in as a big array, and using += to assign defaults to missing values
This would allow for function calls that more closely mimick thoes made in javascript using JSON, with enough work, it could be almost identical using associative arrays
* function callbacks within a class to global instances of other classes
This allows you pass a function callback to an object early on, and hold off its execution until later in the program (say during page outputing after everything has been setup)

public function getInstance () <
return new self ( current ( func_get_args ()));
>

$r = new Runner ( 1 );
$s = new Speaker ( 2 );

Источник

Особенности при перехватах вызовов методов с помощью __call() и __callStatic() в PHP

Пролог

Что такое __call() и __callStatic()?

Начнём с простого: у вас есть класс, описывающий методы и свойства какого-либо объекта (что, в принципе, логично). Представьте, что вы решили обратиться к несуществующему методу этого объекта. Что вы получите? Правильно — фатальную ошибку! Ниже привожу простейший код.

В статическом контексте наблюдаем аналогичное поведение:

Так вот, иногда возникает необходимость либо выполнить какой-то код при отсутствии нужного нам метода, либо узнать какой метод пытались вызвать, либо использовать другое API для вызова нужного нам метода. С этой целью и существуют методы __call() и __callStatic() — они перехватывают обращение к несуществующему методу в контексте объекта и в статическом контексте, соответственно.
Перепишем наши примеры с использованием «магических методов». Примечание: Каждый из этих волшебников принимает два параметра: первый — имя метода, который мы пытаемся вызвать, второй — список, содержащий параметры вызываемого метода. Ключ — номер параметра вызываемого метода, значение — собственно сам параметр:

Практическое применение этих двух товарищей зависит только от вашей фантазии. В качестве примера, приведу набросок реализации техники программирования Fluent Interface (некоторые считают это паттерном проектирования, но от названия суть не меняется). Коротко говоря, fluent interface позволяет составлять цепочки вызовов объектов (с виду что-то похожее на jQuery). На хабре есть пару статей про реализацию такого рода алгоритмов. На ломаном русском переводе fluent interfaces звучат как «текучие интерфейсы»:

Ты кажется хотел рассказать нам что-то про особенности перехвата?

Обязательно расскажу. Сидя вчера за компьютером, решил систематизировать свои знания по PHP.
Набросал примерно такой кусок кода (в оригинале было чуть по другому, но для статьи сократил, ибо остальное не несло смысловой нагрузки для данной проблемы):

Обновил страничку. Моему удивлению не было предела. Я сразу побежал на php.net смотреть мануал.
Вот выдержка из документации

В контексте объекта при вызове недоступных методов вызывается метод __call().
В статическом контексте при вызове недоступных методов вызывается метод __callStatic().

Я долго не мог понять в чём проблема. Версия PHP: 5.4.13. То есть те времена, когда вызовы несуществующих методов из любого контекста приводили к вызову __call() давно прошли. Почему вместо логичной Fatal Error, я получаю вызов __call()? Я пошёл исследовать дальше. Добавил в абстрактный класс Base метод __callStatic(). Снова обновил страницу. Вызов по-прежнему адресовался в __call(). Промучавшись полдня, всё-таки понял в чём была проблема. Оказывается PHP воспринимает статический контекст внутри класса и вне его по-разному. Не поняли? Попытаюсь проиллюстрировать. Возьмём предыдущий пример и добавим в него одну строчку:

То есть статический контекст — статическому контексту рознь.
Чудеса да и только. Когда я изучал «магические методы», я не думал, что название стоит воспринимать настолько буквально.

Ну здесь становится уже всё понятно: если мы добавим метод __callStatic() в класс Base приведённого выше примера, то вместо вывода фатальной ошибки, PHP выполнит __callStatic().

Резюме

Если для вас ещё не всё понятно: речь идёт о том, что обращение к статическому методу внутри экземпляра класса и обращение к статическому методу вне экземпляра класса — воспринимаются интерпретатором по-разному. Если вы поменяете self::Launch() на Main::Launch() контекст вызова не изменится. Поведение в этом случае будет одинаковым. Опять же, проиллюстрирую:

Итог статьи прост: будьте внимательными (впрочем, как и всегда) и проверяйте поведение при вызовах методов.

Источник

call_user_func

(PHP 4, PHP 5, PHP 7, PHP 8)

call_user_func — Вызывает callback-функцию, заданную в первом параметре

Описание

Список параметров

Ноль или более параметров, передаваемые в callback-функцию.

Учтите, что параметры для call_user_func() не передаются по ссылке.

Пример #1 Пример использования call_user_func() и ссылки

Результат выполнения данного примера:

Возвращаемые значения

Возвращает значение, возвращённое callback-функцией.

Примеры

Пример #2 Пример использования call_user_func()

Результат выполнения данного примера:

class Foo <
static public function test () <
print «Привет, мир!\n» ;
>
>

Результат выполнения данного примера:

Пример #4 Вызов метода класса с помощью call_user_func()

class myclass <
static function say_hello ()
<
echo «Привет!\n» ;
>
>

$myobject = new myclass ();

Результат выполнения данного примера:

Пример #5 Использование лямбда-функции с call_user_func()

Результат выполнения данного примера:

Примечания

Смотрите также

User Contributed Notes 31 notes

I benchmarked the comparison in speed between variable functions, call_user_func, and eval. My results are below:

Variable functions took 0.125958204269 seconds.
call_user_func took 0.485446929932 seconds.
eval took 2.78526711464 seconds.

This was run on a Compaq Proliant server, 180MHz Pentium Pro 256MB RAM. Code is as follows:

function fa () < return 1 ; >
function fb () < return 1 ; >
function fc ()

$calla = ‘fa’ ;
$callb = ‘fb’ ;
$callc = ‘fc’ ;

if you simply want to dynamically call a method on an object it is not necessary to use call_user_function but instead you can do the following:

$obj = new ClassName ();

?>

I’ve used the above so I know it works.

@insta at citiesunlimited dot com & @Maresa

call_user_func() alleged slowness is quite over estimated when it comes to real use cases. we are talking about loosing fraction of a second every million calls, which by the way would take less than half a sec to execute in the worst case.

I don’t know of many processes that would actually suffer from this kind of overhead.

You don’t need to use this function to call a variable class function. Instead you can do the following:

The example works in PHP 5 from within the class. It is the <> that do the trick.

>phil at gettcomm dot com
>22-May-2002 04:51
>if you need to get a reference back from a method, you can work around
>call_user_func()’s shortcomings like this:
>
Naaa! Having back a reference is a real problem, but it can be solved by mean of eval(), instead of using call_user_func:

An entirely OO solution to add dynamicly methods to classes, I used in a project:
class ProductPart <

With this class, you can dynamicly add and remove classes by calling register or unregister. Register will store the object in an associative array by calling toString (as defined by ProductPlugin) and saving the method under the returned string in the array. (In this case the name of the method the class adds.)

When a method is called, which isn’t standard in the object, _call will lookup the called method in the array. If found, __call run the method of the plugin with the provided arguments. I restricted the user provided argument to 1, because I want to force the user to use associative arrays.

Because I chose an array to store my classes, removing a function is quite simple. However the unregister function isn’t optimal, I better pass a string instead of a plugin object. I didn’t test it yet on performance.

The ProductPlugin class:

?>

And at last some demonstration code:

Источник

call_user_method

call_user_method — Вызывает метод указанного объекта

Эта функция объявлена УСТАРЕВШЕЙ в PHP 4.1.0, и УДАЛЕНА в PHP 7.0.0.

Есть следующие альтернативы:

Описание

Список параметров

Имя вызываемого метода.

Примеры

Пример #1 Альтернатива call_user_method()

Смотрите также

User Contributed Notes 5 notes

It does not work to use Pointers as Arguments:

This function is very similar to this:

You can pass a variable number of parameters to a function, use a definition like:

and then you can pass 2, 3 or 4 parameters. This is explained in the «Functions» section of the manual.

See also the PHP4 functions: func_num_args(), func_get_arg(), and func_get_args(), and examples therein

From what i’ve observed, call_user_func() does everything this funciton does and a little more. I made a pretty good example call_user_func()’s usage with object instances and figured it might be useful here:

This is a demonstration of 2 neat features of PHP

* passing array arguments in as a big array, and using += to assign defaults to missing values
This would allow for function calls that more closely mimick thoes made in javascript using JSON, with enough work, it could be almost identical using associative arrays
* function callbacks within a class to global instances of other classes
This allows you pass a function callback to an object early on, and hold off its execution until later in the program (say during page outputing after everything has been setup)

public function getInstance () <
return new self ( current ( func_get_args ()));
>

$r = new Runner ( 1 );
$s = new Speaker ( 2 );

Источник

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

call_user_func_array — Вызывает callback-функцию с массивом параметров

Описание

Список параметров

Передаваемые в функцию параметры в виде индексированного массива.

Возвращаемые значения

Возвращает результат функции или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования функции call_user_func_array()

Результатом выполнения данного примера будет что-то подобное:

Пример #2 Пример использования call_user_func_array() c именем пространства имён

Результатом выполнения данного примера будет что-то подобное:

Пример #3 Использование лямбда-функции

Результат выполнения данного примера:

Пример #4 Передача значений по ссылке

Результат выполнения данного примера:

Примечания

Смотрите также

User Contributed Notes 38 notes

As of PHP 5.6 you can utilize argument unpacking as an alternative to call_user_func_array, and is often 3 to 4 times faster.

Just hope this note helps someone (I killed the whole day on issue).

I just pulled my hair out with an old installation of CakePHP because it was passing NULL instead of an empty array.

For anyone looking for the means to test for the first parameter before passing to this function, look at the is_callable (http://php.net/manual/en/function.is-callable.php) variable handler.

It appears that when PHP executes something like:

suddenly, inside foo, the second parameter is passed by reference!

And you can’t call this wrong, only another subtly of references.

Note it appears that ksort($a) will remove the reference as well as put the elements in key order so you (probably) get what you expect. (see below on the use of a foreach ($a as &v).)

$f = new foo_bar3 ( «abc» );

?>

Instead, use the direct name of the class as string or, better, the magic constant __CLASS__ in call_user_func_array(), like:

Then the parameters will be correctly redirected to the lowest base class.

Since PHP 5.6 you can use the spread operator (argument unpacking) instead of call_user_func_array().

$param_arr may be empty, though it can’t be null.

Note the code here is an example of usage. The actual hack is denoted by comments.
If someone knows a better alternative, by all means, i would love to see it.

call_user_func_array can pass parameters as reference:

Be aware the call_user_func_array always returns by value, as demonstrated here.

Here is a function you can use in place of call_user_func_array which returns a reference to the result of the function call.

call_user_func_array() is nifty for calling PHP functions which use variable argument length. For example:

There’s a possibility that call_user_func_array(), call_user_func(), and Exception::getTrace() will cause a trace entry to not have the ‘file’ or ‘line’ elements.

I came up with a better solution to the problem that I solve below with createObjArray that maintains parameter type:

?>

Would be good to add error checking, but it works.

Regarding the comments below about calling parent constructors:

PHP5 with E_STRICT no longer allows calls as below:

Note that call_user_func() will completely trash debug_backtrace().

?>

Note the 3 dots (array unpacking syntax).

PLS notice that «patripaq at hotmail dot com» ‘s code will be valid if B EXTENDS A.
class B extends A <
.
>
?>
there>>»What I wanted to do is create an object that can manage any number and any kind of parameters.»

BUT IT IS NOT A POINT AT ALL

If you need to call just function with parameters:
call_user_func_array(‘Foo’,$args);

If you need to call CLASS method (NOT object):
call_user_func_array(array(‘class’, ‘Foo’),$args);

If you need to call OBJECT method:
call_user_func_array(array(&$Object, ‘Foo’),$args);

If you need to call method of object of object:
call_user_func_array(array(&$Object->Object, ‘Foo’),$args);

If you need to call object method from within the very same object (NOT CLASS!):
call_user_func_array(array(&$this, ‘Foo’),args);

The call_user_func_array ITSELF can manage any number and any kind of parameters. It can handle ANY FUNCTION too as it is defined and that maybe partipaq wanted to manage.

For those of you that have to consider performance: it takes about 3 times as long to call the function this way than via a straight statement, so whenever it is feasible to avoid this method it’s a wise idea to do so.

Note that eval() is about 10 times slower than a straight statement to call a function with arguments, so this is definitely a better option than using eval() even if you only consider performance.

An implementation where parameters are submitted by their name.
This function calls class functions, class methods, functions and anonymous functions.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *