简体   繁体   English

从变量创建类并使用它扩展另一个类?

[英]Creating a Class from a Variable and Using it to Extend Another Class?

I'm using a plugin in wordpress which requires each shortcode I define to be used to extend a function. 我在wordpress中使用一个插件,该插件需要定义的每个短代码都可以用于扩展功能。 I've set up my code in a way which means it's going to be difficult to go back and extend all the classes. 我以某种方式设置我的代码,这意味着将很难返回并扩展所有类。 For example, the plugin expects this: 例如,插件期望这样:

class WPBakeryShortCode_myCode extends WPBakeryShortCodesContainer {}

I want to replace 'myCode' with a variable, because I have all the possible codes stored in an array. 我想用变量替换“ myCode”,因为我将所有可能的代码存储在数组中。 so I want to have 所以我想要

class WPBakeryShortCode_$customCode extends WPBakeryShortCodesContainer {}

ie using a variable to define a class which then extends another class. 即使用变量定义一个类,然后扩展另一个类。 Every way I've tried this I've gotten an error. 我尝试过的每种方式都出错了。 Any ideas how I can do this? 有什么想法可以做到吗?

You cant instantiate one at runtime from a variable. 您不能在运行时从变量实例化一个。

There's no recommended way to dynamically do that because the generated class has to be instantiated before the variable is evaluated 没有推荐的方法来动态地执行此操作,因为在评估变量之前必须实例化生成的类

Using Eval is bad practice and its not recommended , if you want to know how here is example 如果您想知道这里的示例,那么使用Eval是不好的做法, 不建议使用

akshay@db-3325:/tmp$ cat test.php 
<?php

class A { }
class B { 
     function iamB(){
         print "From B".PHP_EOL;
     }
}

$myvariable = 'B';  


$code =<<<EOF
  class C extends $myvariable { 
    public static function bar(){
      print "not recommended".PHP_EOL; 
    }
  }
EOF;

eval( $code );

C::iamB();
C::bar();

?>

Output 产量

akshay@db-3325:/tmp$ php test.php 
From B
not recommended

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

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