动态 PHP 方法

Dynamic PHP Methods

我正在 PHP 中开发自定义数据库 Table 映射器。 是否可以在 PHP 中创建类似 "virtual methods" 的内容来访问属性?像方法一样,实际上并不存在。

例如:A class "user" 有 属性 "$name",我不想为此创建一个 "Get" 方法,但是我想通过虚拟方法访问 属性,如下所示:$user->GetName();

我正在考虑使用约定。因此,每次调用 "virtual" 方法时,您都会捕获它,并检查它是否具有前缀 "Get" 或 "Set".

如果它有前缀 "Get",你去掉 "Get" 之后的部分,把它变成小写,这样你就有了你想要访问的 属性。

我的想法(伪代码):

public function VirtualMethodCalled($method_name)
{
   //Get the First 3 Chars to check if Get or Set
   $check = substr($method_name, 0, 3);

   //Get Everything after the first 3 chars to get the propertyname
   $property_name = substr($method_name, 3, 0);

   if($check=="Get")
   {
       return $this->{$property_name};
   }
   else if($check=="Set")
   {
       $this->{$property_name};
       $this->Update();
   }
   else
   {
       //throw exc
   }
}

你可以使用魔法来实现,例如:

class A {

    private $member;


    public function __call($name, $arguments) {
      //Get the First 3 Chars to check if Get or Set
      $check = substr($method_name, 0, 3);

     //Get Everything after the first 3 chars to get the propertyname
     $property_name = substr($method_name, 3);

     if($check=="Get")
     {
       return $this->{$property_name};
     }
     else if($check=="Set")
     {
       $this->{$property_name} = $arguments[0]; //I'm assuming
     }
     else
     {
         //throw method not found exception
     }
    }
}

我主要是使用你提供的内容代码。您显然可以扩展它来处理函数名称别名或任何您需要的东西。