我编写了一个自动加载类的代码,我遇到了一个问题,我认为是因为弱点实现/设计类型。我想要做的是计算对象的默认参数(外部)。 我可以计算构造函数传递的参数的数量,但我需要检查内部对象构造函数,并且该方法对我没有帮助。
代码示例:
// This is simple
function test($arg1,$arg2,$arg3) {return func_num_args();}
// How can I count like this?
class load
{
public function __construct($id="",$path="") {}
}
$l = new load();
// How to count object default parameters count(object($l)), I need answer to be 2`
我需要使用此方法的代码:
[文件:global_cfg.php]
<?php
// File: global_cfg.php
define(ROOT, __DIR__); // Root directory
define(DEBUG, true); // Set debugging state ON or OFF
define(MODE, "producer"); // If debug mode is ON: producer, publisher, tester
/*
* PATH CONFIGURATIONS:
*/
define(DS, "/");
define(LIB, "library");
/*
* SIGN AUTOLOAD CLASSES:
* Setting class sign to true value, the autoloader will create automatically
* an instance of the class lowercase type.
*/
$signClasses = Array
(
"Ralor" => false,
"NaNExist" => true,
"Message" => array(MODE),
"Debug" => DEBUG,
"Resource" => true,
"View" => true
);
[File:autoload_classes.php]
<?php
// File: autoload_classes.php
require_once("global_cfg.php");
print "<b>Loaded classes:</b> <br>";
function __autoloadClasses($list, $suffix="class", $extension="php")
{
$path="";
foreach($list as $fileName => $classInstance)
{
$path = ROOT.DS.LIB.DS.$fileName.".".$suffix.".".$extension;
if(!file_exists($path))
{
print "Signed class ".$fileName." does not exist!<br>";
continue;
}
require_once($path);
print $path;
if($classInstance)
{
$GLOBALS[strtolower($fileName)] = new $fileName();
// ??? todo: counting default object parameters
$count = count(get_object_vars($GLOBALS[strtolower($fileName)]));
if(is_array($classInstance))
{
if($count<count($classInstance))
{
print "Arguments passed to object exceeds the limit";
}
else if($count>count($classInstance))
{
print "Insuficient arguments passed to the object!";
}
else
{
// todo: create object and pass parameters
$GLOBALS[strtolower($fileName)] = new $fileName(/*$arg1 .. $argn*/);
}
}
print $count." -> Class was instantiated!<br>";
continue;
}
print "<br>";
}
}__autoloadClasses($signClasses);
在这个问题之后,我可以完成我的引导程序。
答案 0 :(得分:4)
您可以使用ReflectionFunctionAbstract::getNumberOfParameters。例如。
class load
{
public function __construct($id = "", $path = "")
{
}
}
function getNumberOfParameters($class_name)
{
$class_reflection = new ReflectionClass($class_name);
$constructor = $class_reflection->getConstructor();
if ($constructor === null)
return 0;
else
return $constructor->getNumberOfParameters();
}
var_dump(getNumberOfParameters('load'));