user4181107
user4181107

Reputation: 401

What does the array payload mean in the context of some_function(array($this, 'something'))

While looking at code online or as part of examples or tutorials, I sometimes see some_function(array($this, 'something')) what does that mean? I've never seen array syntax like that and it really confuses me.

One example is this code from a comment in the manual:

<?php

    class ClassAutoloader {
        public function __construct() {
            spl_autoload_register(array($this, 'loader'));
        }
        private function loader($className) {
            echo 'Trying to load ', $className, ' via ', __METHOD__, "()\n";
            include $className . '.php';
        }
    }

    $autoloader = new ClassAutoloader();

    $obj = new Class1();
    $obj = new Class2();

?>

Can someone please explain what that syntax means?

Upvotes: 1

Views: 64

Answers (4)

EyeSpy
EyeSpy

Reputation: 215

some_function(array($this, 'something')) 

is just a function you call and as parameter you give it an array

it could be rewritten to this

some_function([$this, 'something'])

or

$arr = array($this, 'something');
some_function($arr);

Upvotes: 0

tkausl
tkausl

Reputation: 14279

This is the usual array-syntax in PHP. You're probably confused, because it is not saved in a variable but passed directly. To clarify this,

spl_autoload_register(array($this, 'loader'));

is equivalent to

$array = array($this, 'loader');
spl_autoload_register($array);

and to

$array = array();
$array[0] = $this;
$array[1] = 'loader';
spl_autoload_register($array);

Upvotes: 1

arkascha
arkascha

Reputation: 42925

Well it hands over a single parameter to the function spl_autoload_register(). The parameter is of type array and contains two elements. The first one is the object that calls the function, the second is a string.

Upvotes: 0

blockhead
blockhead

Reputation: 9705

This is a PHP callable. It means call the method loader on the object $this.

Here is a link with more information: http://php.net/manual/en/language.types.callable.php

Upvotes: 1

Related Questions