You must have to understand the oops concepts here.
$this refers to your current class / object. So all functions inside a class will be able to access $this ( Current Object ).
But the function declared out side of class can not use $this of that object. (Are you clear up to here.)
But anyways nothing is impossible.
You can achieve your goal in at-least 2 ways.
2) You can use trait to implement multiple inheritance.
it will be like this
trait commonFunctions
{
function add($a, $b)
{
$this->result = $a + $b;
return $this;
}
}
class myClass
{
use commonFunctions;
public function myClassFunction()
{
//
}
}
2 ) Or you can follow below code. Source php.net
<?php
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(), "
";
$cl = $cl->bindTo($ob2);
echo $cl(), "
";
Here __call will be called when undeclared method is being called. So you can dynamically append methods to class by this way.
Of course you can polyfill your object in javascript like way. But keep in mind you need to use Reflection to bind this to closure.
<?php
class A {
private $dynamic_functions=[];
public function __call($method, $args=[])
{
if(isset($this->dynamic_functions[$method]) && $this->dynamic_functions[$method] instanceof \Closure)
{
$cl = $this->dynamic_functions[$method]->bindTo($this);
return call_user_func_array($cl, $args);
}
else
{
die("Wrong method, Not yet polyfilled.");
}
}
public function __set($property, $value)
{
$this->dynamic_functions[$property] = $value;
}
}
$a = new A;
$a->sum = function($a,$b){
// var_dump($this); will give you current instance of A
return $a+$b;
};
echo $a->sum(5, 3);