Answer the question
In order to leave comments, you need to log in
How to assign a function to an object in PHP?
There is an object created on the basis of the class MyClass or stdClass, you need to add one more function to the existing properties and methods. If possible, is it possible to add a function to an uninitialized class?
$std = new stdClass();
$std->GetPrint = function () { echo "Урра !!!";};
$std->GetPrint();
class MyClass{
function GetOther(){ echo "другой метод";}
}
MyClass::GetPrint = function () { echo "Урра !!!";};
$my = new MyClass();
$my->GetPrint();
Answer the question
In order to leave comments, you need to log in
I need to extend the functionality of a CMS with an installed module. The task is that the module and the CMS itself can be freely updated regularly, and my extended functionality hangs as an extension module that does not affect the code of the main program.This is done using the Event Listeners and Event Subscribers approaches.
The only, more or less adequate option is to override the entry point and intercept the autoloading of CMS classes by connecting your module classes that are inherited from the CMS base classes.
I mean, when CMS\Route is called, you intercept this loading by declaring your loader earlier and including MyModule\Route which is inherited from CMS\Route and changing its behavior.
It's bad, and hands are torn off for this, but it's better than execution, for what you want to do :)
class my extends yours {
// Ваш код
}
I don't know if there is access to the original class, but you can always use the trait if PHP >= 5.4.
Plus, the approach that is in the example is possible in such a case (it is clear that there are other options):
class MyClass {
public $GetPrint;
public function GetPrint()
{
if (!empty($this->GetPrint)) {
call_user_func($this->GetPrint, $this);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question