PHP callbacks and anonymous functions

怪我咯
Release: 2023-03-11 18:02:02
Original
887 people have browsed it

Anonymous function is not a strictly object-oriented feature, but it is very useful because you may encounter it in object-oriented applications that use callbacks.

Please look at the following two classes:

<?php
class Product
{
    public $name;
    public $price;

    function construct($name, $price)
    {
        $this->name = $name;
        $this->price= $price;
    }
}

class ProcessSale
{
    private $callbacks;

    function register_callback($callback)
    {
        if(!is_callable($callback))    //判断是否可以调用
        {
            throw new Exception(&#39;callback not callable&#39;);
        }

        $this->callbacks[] = $callback;
    }

    function process($product)
    {
        print "{$product->name}: processing\n";

        foreach($this->callbacks as $callback)
        {
            call_user_func($callback, $product);
        }
    }
}

?>
Copy after login

The purpose of this code is to run various callbacks. Product only stores $name and $price. Processsale consists of 2 methods. registercallback() accepts a silent scalar, tests the scalar and adds it to the callback array. The built-in function that implements the test function is_callable() function, which ensures that the value passed in is called by functions such as call_user_func() or array_walk().

The process() method accepts a product object and outputs a piece of information related to the object. Then iterate through the $callbacks array property.

Advantages of callbacks: You can use callbacks to insert functions that are not directly related to the core tasks of the component into the component at runtime. With component callbacks, you give others the power to extend your code in contexts you don't know about.

Now suppose the user wants to create a sales record. If that user has direct access to the class, you can add logging logic in the process() method, but sometimes this is bad practice. If he is not the maintainer of the class, his changes to the class will be overwritten in the next update. Even if he is the maintainer of this component, adding so many additional tasks to the process() method is putting the cart before the horse and failing to reflect the core functionality of this method, which may reduce the possibility of this method crossing projects.

Fortunately, we created a process callback.

<?php
class Product
{
    public $name;
    public $price;

    function construct($name, $price)
    {
        $this->name = $name;
        $this->price= $price;
    }
}

class ProcessSale
{
    private $callbacks;

    function register_callback($callback)
    {
        if(!is_callable($callback))    //判断是否可以调用
        {
            throw new Exception(&#39;callback not callable&#39;);
        }

        $this->callbacks[] = $callback;
    }

    function process($product)
    {
        print "{$product->name}: processing\n";

        foreach($this->callbacks as $callback)
        {
            call_user_func($callback, $product);
        }
    }
}

$logger = create_function(&#39;$product&#39;, &#39;print " logging ({$product->name})\n";&#39;);
$p1 = new ProcessSale();
$p1->register_callback($logger);

$p1->process(new Product("shoes", 8));
print "\n";

$p1->process(new Product("coffee", 9));
?>
Copy after login

The result runs by itself.

PHP 5.3 and later versions provide a better way to implement anonymous functions.

$logger = function($product)
{
     print " logging ({$product->name})\n";
};

$p1 = new ProcessSale();
$p1->register_callback($logger);

$p1->process(new Product("shoes", 8));
print "\n";

$p1->process(new Product("coffee", 9));
Copy after login

This method uses the function keyword inline and has no function name. Note that because this is an inline statement, a semicolon is required at the end of the code block.

Callbacks do not have to be anonymous, you can use function names (or even object references and methods) as callbacks.

The above is the detailed content of PHP callbacks and anonymous functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!