AL-zami
AL-zami

Reputation: 9076

how to bind THIS to an external function in php

I spent a good amount time learning javascript.Now i've come to php world and felt kind of lost at first when i started learning OOP in php.In javascript i can bind/apply/call external functions to do some specific job.How can i manage this behavior in php?Here i have simple javascript code which uses apply method .How can i do the same thing using php.I know declaration of class is different.And variable visibility is also there.I just want to know is there any way to imitate bind/apply/call functionality in php??

js code is below::

function Person(name,haircolor){
   this.name=name;
   this.haircolor=haircolor;

}

function display(){

  console.log(this.name+' has '+this.haircolor+' hair.');
}

var person1=new Person('zami','black');

display.apply(person1);

Upvotes: 0

Views: 126

Answers (1)

deceze
deceze

Reputation: 522480

Call-time binding is a peculiarity very specific to Javascript (not exclusively, but largely). Most other languages bind the object context before that, irreversibly. The best you could do in PHP is shown in the manual for the Closure class, the internal implementation for anonymous functions:

class A {
    function __construct($val) {
        $this->val = $val;
    }
    function getClosure() {
        //returns closure bound to this object and scope
        return function() { return $this->val; };
    }
}

$ob1 = new A(1);
$ob2 = new A(2);

$cl = $ob1->getClosure();
echo $cl(); // 1
$cl = $cl->bindTo($ob2);
echo $cl(); // 2

It is not possible to bind a function/closure to arbitrary objects; at most you can bind it to other instances of the same class it referred to anyway. It's also possible to do this via ReflectionMethod::invoke. But again, it's really really not the way PHP (and most traditional OOP languages) works and you should never write code in this way for purposes other than curiosity.


this and $this are just another variable. The only thing they do is to implicitly carry state without you needing to pass them into all functions you call. In PHP it further contributes to encapsulation, since $this can have values which are not accessible from outside the class; that's not even the case with Javascript. As such, there's no real need to program this way. Anything you can express with (a theoretical) $foo->bar->apply($baz), you can just as well write as $foo->bar($baz) or bar($baz).

Upvotes: 4

Related Questions