How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below?
<?php
/*
./index.php
*/
function Object($object)
{
static $instance = array();
if (is_file('./' . $object . '.php') === true)
{
$class = basename($object);
if (array_key_exists($class, $instance) === false)
{
if (class_exists($class, false) === false)
{
require('./' . $object . '.php');
}
/*
How can I pass custom arguments, using the
func_get_args() function to the class constructor?
$instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...);
*/
$instance[$class] = new $class();
}
return $instance[$class];
}
return false;
}
/*
How do I make this work?
*/
Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */);
/*
./libraries/DB.php
*/
class DB
{
public function __construct($database, $username, $password, $host = 'localhost', $port = 3306)
{
// do stuff here
}
}
?>
Pass by Value Arguments are passed by value. When invoked, a method or a constructor receives the value of the variable passed in. When the argument is of primitive type, "pass by value" means that the method cannot change its value.
Constructors can be passed as arugments to methods using a method reference, somewhat like a function pointer in C++. This can be a Function type with one argument or a BiFunction type with two arguments, either way its a lambda returning a class of the type it constructs.
It is used to prevent a specific constructor from being called implicitly when constructing an object. For example, without the explicit keyword, the following code is valid C++: Array a = 10; This will call the Array single-argument constructor with the integer argument of 10.
Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function.
$klass = new ReflectionClass($classname);
$thing = $klass->newInstanceArgs($args);
Although the need to use reflection suggests that you are overcomplicating something in your design. Why do you want to write this function in the first place?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With