匿名类建设

Dav*_*ues 9 php namespaces anonymous class php-7

我需要一个在PHP上创建匿名类的想法.我不知道我的工作方式.

看我的局限:

  • 在PHP上你不能像匿名函数那样创建匿名类(如class {});
  • 在PHP上你没有类范围(名称空间除外,但它在下面有相同的问题);
  • 在PHP上,你不能使用变量来指定类名(如class $name {});
  • 我没有权限安装runkitPECL.

我需要什么,为什么:

好吧,我需要创建一个名为ie的函数create_class(),它接收一个键名和一个匿名类.它对我有用,因为我想使用PHP无法接受的不同名称类符号.例如:

<?php

  create_class('it.is.an.example', function() {
    return class { ... }
  });

  $obj = create_object('it.is.an.example');

?>
Run Code Online (Sandbox Code Playgroud)

所以,我需要一个接受这种用法的想法.我需要它,因为在我的框架中我有这条道路:/modules/site/_login/models/path/to/model.php.所以,model.php需要声明一个叫做的新类site.login/path.to.model.

在调用时,create_object()如果内部缓存有一个$class定义(就像it.is.an.example它只是返回新的类对象.如果没有,需要加载.所以我将使用$class内容快速搜索什么是类文件.

Lev*_*son 7

在PHP 7.0中,将有匿名类.我不完全理解你的问题,但你的create_class()功能可能如下所示:

function create_class(string $key, array &$repository) {
    $obj = new class($key) {
        private $key;
        function __construct($key) {
            $this->key = $key;
        }
    };
    $repository[$key] = $obj;
    return $obj;
}
Run Code Online (Sandbox Code Playgroud)

这将实例化一个具有匿名类类型的对象并将其注册到$repository.要获取对象,请使用您创建的密钥:$repository['it.is.an.example'].


Ste*_*wie 6

您可以使用stdClass创建一个虚拟类

$the_obj = new stdClass();
Run Code Online (Sandbox Code Playgroud)

  • 无法将方法附加到`stdClass` (4认同)

Chu*_*urk 6

所以基本上你想要实现一个工厂模式.

Class Factory() {
  static $cache = array();

  public static getClass($class, Array $params = null) {
    // Need to include the inc or php file in order to create the class
    if (array_key_exists($class, self::$cache) {
      throw new Exception("Class already exists");
    }

    self::$cache[$class] = $class;
    return new $class($params);
  }
}

public youClass1() {
  public __construct(Array $params = null) {
     ...
  }
}
Run Code Online (Sandbox Code Playgroud)

在其中添加缓存以检查重复项