FitzChevalerie
FitzChevalerie

Reputation: 29

What exactly is '$this" in add_action()

Some add_action() statements that i see now and then are provided with an array in which the first argument is $this, and the second one, the function.

As far as i know, $this stands as the current instance in POO, but what about in this particular case? Let's say for the sake of example that we have a newsletter system that registers your email adress, except if it still exists in the database.

<?php
public function save_email()
{
    if (isset($_POST['zero_newsletter_email']) && !empty($_POST['zero_newsletter_email'])) {
        global $wpdb;
        $email = $_POST['zero_newsletter_email'];

        $row = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}zero_newsletter_email WHERE email = '$email'");
        if (is_null($row)) {
            $wpdb->insert("{$wpdb->prefix}zero_newsletter_email", array('email' => $email));
        }
    }
} 

Now we need to declare it as an available action. why should we need an array like this one?

add_action('wp_loaded', array($this, 'save_email'));

And why couldn't we simply do as followed?

add_action('wp_loaded','save_email');

Upvotes: 1

Views: 555

Answers (2)

Danny Battison
Danny Battison

Reputation: 533

Because save_email is a class method and we're adding the action from $this class instance (i.e. from within the class owning the method).

The array represents a PHP callable, see type 3 in the example: http://php.net/manual/en/language.types.callable.php

Upvotes: 1

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21671

This is too long for a comment.

$this is the current instance of the current class. So it would be the instance invoking the hook. Or the class the action is being added in.

add_action('wp_loaded', array($this, 'save_email'));

So this is the save email in the current class.

And why couldn't we simply do as followed?

add_action('wp_loaded','save_email');

Because you can't ... Just kidding.

this is due to using call_user_func_array

http://php.net/manual/en/function.call-user-func-array.php

Which is the built in way of doing it. I am sure it also has to do with how functions are called, because without the class it would be ambiguous if this was a function or a method of a class.

In the case you present, PHP would think that was a function. Even if there was a way to tell it, it wasn't, how would you tell it what class that method is in. So it's easier and safer to just put the class in...

Upvotes: 0

Related Questions