简体   繁体   English

动态PHP方法

[英]Dynamic PHP Methods

I am working on a custom DB Table Mapper in PHP. 我正在使用PHP中的自定义数据库表映射器。 Is it possible in PHP to make something like "virtual methods" to access the properties? 是否有可能在PHP中使用“虚拟方法”来访问属性? Like Methods, that don't really exist. 像方法一样,那些并不存在。

For Example: A class "user" has the property "$name", i don't want to create a "Get" Method for this one, but i want to access the property via a virtual Method, like this: $user->GetName(); 例如:类“user”具有属性“$ name”,我不想为此创建“Get”方法,但我想通过虚拟方法访问该属性,如下所示:$ user- >的GetName();

I was thinking of working with Conventions. 我正在考虑与公约合作。 So everytime a "virtual" Method has been called, you catch it, and check if it has the prefix "Get" or "Set". 因此,每次调用“虚拟”方法时,都会捕获它,并检查它是否具有前缀“Get”或“Set”。

If it has the prefix "Get" you strip the part after "Get" and make it lowercase, so you have the property you want to access. 如果它具有前缀“Get”,则在“Get”之后剥离部件并将其设置为小写,因此您具有要访问的属性。

My Idea (Pseudo Code): 我的想法(伪代码):

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
   }
}

You can use a magic method to achieve this, example: 您可以使用魔术方法来实现此目的,例如:

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
     }
    }
}

I'm mainly using the code you provided for the contents. 我主要使用您为内容提供的代码。 You can obviously extend this to also handle things like function name aliases or whatever you need. 显然,您可以将其扩展为处理函数名称别名或任何您需要的内容。

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

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