我已经回顾了PHP魔术方法,但至少从这些方法中看不到任何方法来实现这一目标。
我想有一种方法"神奇地"当任何类被实例化时调用,类似于__onClassCall()
,这不是专门写在类中的 - 这将用于调试,我想打开或关闭它。类似地,我想在调用类中的任何方法时触发另一个方法,这可以在其他地方写入并打开或关闭。这可能吗?
答案 0 :(得分:0)
您可能希望自己实施这些功能。 __invoke()
魔法可能不是你需要的,因为你还是必须明确地触发它。请考虑下面的代码,其中您有MagicHelper
类,其中您声明了Magic方法,然后在您的类中使用它们(此处:SomeClassOne
)。这可能不是内置的PHP函数,但这就是OOP的全部内容,对吧?
<?php
class MagicHelper{
public static function __onClassCall(){
// LOGIC FOR SOME SPECIAL INITIALIZATION ON THE INSTANTIATION OF A CLASS OBJECT GOES HERE...
// THIS METHOD IS FIRED EACH TIME AN OBJECT IS INSTANTIATED
}
public static function __onMethodCall(){
// LOGIC FOR DEBUGGING GOES HERE...
// THIS METHOD IS FIRED EACH TIME A METHOD IS CALLED
}
}
class SomeClassOne{
private $prop;
public static $CLASS_PREP_ENABLED = true; //<== COULD BE TURNED OFF OR ON
public static $METHOD_DEBUG_ENABLED = true; //<== COULD BE TURNED OFF OR ON
public function __construct($prop = null) {
$this->prop = $prop;
if(self::$CLASS_PREP_ENABLED){
// CALL THE STATIC MAGIC __onClassCall METHOD DECLARED IN THE MagicHelper CLASS
// EACH TIME A NEW OBJECT IS INSTANTIATED
MagicHelper::__onClassCall();
}
}
function __invoke() {
// YOU COULD AS WELL USE THIS BUT I DOUBT THIS FITS YOUR DESCRIPTION.
}
public function getProp() {
return $this->prop;
}
public function setProp($prop) {
$this->prop = $prop;
return $this;
}
public function methodOne($paramOne){
// THE LOGIC FOR THIS METHOD GOES HERE
//...
// CALL THE STATIC MAGIC __onMethodCall METHOD DECLARED IN THE MagicHelper CLASS
// EACH TIME A NEW OBJECT IS INSTANTIATED
if(self::$METHOD_DEBUG_ENABLED) {
MagicHelper::__onMethodCall();
}
}
public function methodTwo($paramTwo){
// THE LOGIC FOR THIS METHOD GOES HERE
//...
// CALL THE STATIC MAGIC __onMethodCall METHOD DECLARED IN THE MagicHelper CLASS
// EACH TIME A NEW OBJECT IS INSTANTIATED
if(self::$METHOD_DEBUG_ENABLED) {
MagicHelper::__onMethodCall();
}
}
}