如何为"几乎"相同的代码提供大量类方法

ahm*_*med 2 php oop

我有这个PHP类

   class myclass{
       function name($val){
           echo "this is name method and the value is".$val;
       }

       function password($val){
           echo "this is password method and the value is".$val;
       }
   }
Run Code Online (Sandbox Code Playgroud)

以下是如何使用它:

  $myclass= new myclass();
  $myclass->name("aaa")//output: this is name method and the value is aaa
Run Code Online (Sandbox Code Playgroud)

它工作正常,因为我只有2个方法"名称"和"密码"什么如果我有大量的方法,将这些方法添加到我的类并为每个方法编写相同的代码是不容易的,我想更改我的类,让每个方法提供除方法名称之外的相同输出?而且我不想为所有方法编写所有细节,因为它们几乎相似,这在PHP中是否可行?我希望我很清楚:)

Rob*_*Rob 14

您可以覆盖__call()类的方法,这是一种"魔术方法",将在调用不存在的方法时使用.