user2707590
user2707590

Reputation: 1126

anonymous function in php similar like jquery

Does anyone know how jquery functions and anonymous functions are defined? i am trying to create a little class in php to be used the same way as in jquery. for example:

$('.blabla').click(function()
{
   console.log($(this).attr('id');
});

and in php how would the class be like to do this?

$object->click(function()
{
   var_dump($this->attr('id');
});

is this possible? im trying to understand anonymous functions so i can know when to really use it.

Upvotes: 1

Views: 237

Answers (2)

user1320635
user1320635

Reputation:

Yes you can in php 5.3 or above, you can read the documentation here: http://php.net/manual/en/functions.anonymous.php

It doesn't work exactly like JavaScript tough. JavaScript is a prototypal language, php is not.

You can do this in JavaScript:

var value = 'foo';
object.doSomething(function () {
    console.log(value);
});

You can do that because JavaScript functions has a reference to it's creator. In php you cannot. The value would be out of scope.

Other than that, it works kind of similar. For example, if you want to make dynamic iterations over arrays or other structures.

function iterateOverArray($array, $function) {
    foreach ($array as $key => $value) {
        $function($key, $value);
    }
}

That function allows you to iterate over an array and specify your own action. For example:

$array = array('foo', 'bar', 'FOBAR');
iterateOverArray($array, function ($key, $value) {
    echo $key . ' => ' . $value;
});

This is very useful to modify complex structures. But that's the only situation I've used anonymous functions in php. But maybe that's because it's still kind of new in php.

Upvotes: 0

Barmar
Barmar

Reputation: 781761

To call the function your method receives as an argument, it would be like this:

function click($callback) {
    // Do stuff...
    $callback();
    // Do more stuff...
}

PHP doesn't have anything analogous to Javascript's special variable this. $this can only be used in class methods, not other functions. If you want the callback to have access to that variable, you should pass it as an explicit argument.

Upvotes: 1

Related Questions