产生从动态输入新的PHP对象(laravel / octobercms)

问题描述 投票:0回答:2

在laravel对象:

use AAA;
use BBB;
use CCC;
...

从输入获得的名称:“AAA ...”;

$from_input = $some_input;

我可以做到这一点:

$obj = new $from_input;
return $obj::where('status', 1)->get();

“新”功能无法找到类“AAA”

strval没有帮助。请指教。

php laravel object octobercms
2个回答
2
投票

安全提示由于允许终端用户通过此方法实例化任何类的不安全感,我强烈建议不要在底部这样做的,按照我的例子。

进口类都不能在运行时进行评估。你必须使用完整路径类动态实例作为本例所示:

<?php

namespace One {
    use Two\B;

    class A {
        function __construct($className) {
            echo "Attempting to construct $className..";
            new $className;
        }
    }

    new A(B::class); // Works since the B import is evaluated before runtime.
    try {
        new A("B"); // Doesn't work since "B" is not evaluated until runtime
    }
    catch (\Throwable $e) {
        echo $e->getMessage() . "\n";
    }
    new A("Two\B"); // Works since you use the full path to B.
}

namespace Two {
    class B {
        function __construct() {
            echo "B constructed!\n";
        }
    }

}

https://3v4l.org/LTdQN


当你能做到这一点,这是自找麻烦。什么会阻止从检索数据了一些模型,他们不应该访问的人吗?

取而代之的是,建立可用类的数组,并让他们通过数组键,而不是通过类的名称。

$classes = [
   'a' => AAA::class,
   'b' => BBB::class,
   'c' => CCC::class,
];

// $from_input being a, b, or c
if (isset($classes[$from_input])) {
   $obj = new $classes[$from_input];
}

1
投票

你可以调用IoC容器将建立你与任何注入依赖的对象。

$obj = app()->make($from_input)

或者干脆

$obj = app($from_input)

© www.soinside.com 2019 - 2024. All rights reserved.