Alix Axel
Alix Axel

Reputation: 154513

Passing arguments to the Class Constructor

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
    }
}

?>

Upvotes: 9

Views: 13976

Answers (4)

Syntaqx
Syntaqx

Reputation: 9

An alternative for the reflection method, would be evaluate your code.

eval('$instance = new className('.implode(', ', $args).');');

Upvotes: 0

troelskn
troelskn

Reputation: 117417

$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?

Upvotes: 14

staticsan
staticsan

Reputation: 30555

I haven't tried this, but call_user_func_array sounds like you want.

$thing = call_user_func_array(array($classname, '__construct'), $args);

Have a look in the PHP Documentation.

Upvotes: 0

The Pixel Developer
The Pixel Developer

Reputation: 13430

Instead of your class taking separated parameters I'd have it take an array.

class DB
{
    public function __construct(array $params)
    {
        // do stuff here
    }
}

That way you can pass the direct result of the func_get_args into your constructor. The only problem now is being able to figure out the array key / values.

If anyone else has any ideas I'd also be delighted to know :)

Upvotes: 3

Related Questions