PHP 将参数动态传递到类的构造函数中



我在项目的框架中编写了一个PHP类,该类包含一个构造函数,为了这个类的目的,它包含一个名为name的参数。

作为我正在构建的功能的一部分,我的类是动态加载的,我需要从数组中将一个值加载到我的参数中,但当我这样做时,即使我使用array_values,它也只能作为Array出现,例如,下面是我的类:

<?php
class GreetingJob
{
/**
* The name
*/
public $name;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* Write data to a file
*/
public function writeToFile($data = '')
{
$file = fopen('000.txt', 'w');
fwrite($file, $data);
fclose($file);
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
try {
$this->writeToFile('Hello ' . $this->name);
} catch (Exception $e) {
// do something
}
}
}

装载位置:

/**
* Get the job
*/
public function getJob($job = '') {
return APP . "modules/QueueManagerModule/Jobs/$job.php";
}
/**
* Check that the job exists
*/
public function jobExists($job = '') {
if (!file_exists($this->getJob($job))) {
return false;
}
return true;
}
/**
* Execute the loaded job
*/
public function executeJob($class, $rawJob = [], $args = []) {
require_once $this->getJob($class);
$waitTimeStart = strtotime($rawJob['QueueManagerJob']['available_at']) / 1000;
$runtimeStart = microtime(true);
// initiate the job class and invoke the handle
// method which runs the job
$job = new $class(array_values(unserialize($args)));
$job->handle();
}

$args看起来像这样:

[
'name' => 'john'
]

如何按照args的出现顺序将其动态传递给类,并使用每个args的值。

array_values((仍然返回一个数组。它所做的一切都是将键重置为连续的零基整数。

我想你想使用splat操作符:

$job = new $class(...array_values(unserialize($args)));

完整的可运行示例:

<?php
class GreetingJob
{
public function __construct($name)
{
var_dump($name);
}
}
$class = 'GreetingJob';
$args = serialize(
[
'name' => 'Jimmy',
]
);
$job = new $class(...array_values(unserialize($args)));

注意整体设计可能会令人困惑。接受关联数组中的参数表明名称很重要,而位置则不重要,但情况恰恰相反。

这是在php:中使用反射动态实例化类的方法

$className = 'GreetingJob';
$args = [];
$ref = new ReflectionClass($className);
$obj = $ref->newInstanceArgs($args);

https://www.php.net/manual/en/reflectionclass.newinstanceargs.php

最新更新