php - 检查一个类的实例是否存在,如果不存在则创建一个实例

标签 php class autoload

我想知道是否可以创建一个函数并向它传递一个类名。然后该函数检查该类的实例当前是否存在,如果不存在,则创建该类的实例。此外,如果可能的话,使该变量成为全局变量并要求返回它。我意识到返回可能是唯一的选择。

 function ($class_name) {
      // Check if Exists
      // __autoload will automatically include the file
      // If it does not create a variable where the say '$people = new people();'
      $class_name = new $class_name();

      // Then if possible make this variable a globally accessible var. 
 }

这是可能的还是我疯了?

最佳答案

eval 几乎是唯一的方法。确保这不是由用户输入提供的,例如来自 $_GET$_POST 值,这一点非常重要。

function create_or_return($class_name) {
  if(! class_exists($class_name)) {
    eval("class $class_name { }");
    // put it in the global scope
    $GLOBALS[$class_name] = new $class_name;
  }
}

create_or_return("Hello");
var_dump($GLOBALS['Hello']);
/*
    class Hello#1 (0) {
    }
*/

你不能真正让它全局访问,因为 PHP 没有像 javascript 那样的全局对象。但是你不能简单地制作一个容器来容纳物体。

关于php - 检查一个类的实例是否存在,如果不存在则创建一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23160509/

相关文章:

php - 在 Laravel 5 单元测试中找不到特征

javascript - 试图将数据从 .php 文件传递​​到 .js 文件

php - 带有子查询的 PDOStatement 查询返回空结果

php - Laravel - 更改 created_at 以使用 unix 时间戳

c++ - 如何使用 const 成员构造动态数量的类?

php - Silex,加载自己的类

当 Crontab 执行脚本时,PHP Zip 存档提取不工作

C# 新数组。带构造函数的类

c++ - 快速 C++ 类混淆 : What does this line mean?

php - 找不到 fatal error 类 MainController