简体   繁体   English

在方法调用之前调用函数

[英]call a function before method call

Design question / PHP: I have a class with methods. 设计问题/ PHP:我有一个方法类。 I would like to call to an external function anytime when any of the methods within the class is called. 当调用类中的任何方法时,我想随时调用外部函数。 I would like to make it generic so anytime I add another method, the flow works with this method too. 我想把它变成通用的所以当我添加另一个方法时,流程也适用于这个方法。

Simplified example: 简化示例:

<?php

function foo()
{
    return true;
}

class ABC {
    public function a()
    {
        echo 'a';
    }
    public function b()
    {
        echo 'b';
    }
}

?>

I need to call to foo() before a() or b() anytime are called. 我需要在调用a()或b()之前调用foo()。

How can I achieve this? 我怎样才能做到这一点?

Protect your methods so they're not directly accessible from outside the class, then use the magic __call() method to control access to them, and execute them after calling your foo() 保护你的方法,使它们不能从类外部直接访问,然后使用magic __call()方法来控制对它们的访问,并在调用你的foo()后执行它们

function foo()
{
    echo 'In pre-execute hook', PHP_EOL;
    return true;
}

class ABC {
    private function a()
    {
        echo 'a', PHP_EOL;
    }
    private function b($myarg)
    {
        echo $myarg, ' b', PHP_EOL;
    }

    public function __call($method, $args) {
        if(!method_exists($this, $method)) {
            throw new Exception("Method doesn't exist");
        }
        call_user_func('foo');
        call_user_func_array([$this, $method], $args);
    }
}

$test = new ABC();
$test->a();
$test->b('Hello');
$test->c();

You need to use __invoke() method of your class 您需要使用类的__invoke()方法

class ABC {
  public function __invoke()
  {
       //Call your external function here
  }
  public function a()
  {
       echo 'a';
  }
  public function b()
   {
       echo 'b';
   }
}

For your reference : http://php.net/manual/en/language.oop5.magic.php#object.invoke 供您参考: http//php.net/manual/en/language.oop5.magic.php#object.invoke

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM