1

Is there a function I can use to instantiate an object with arguments?

#include <database.h>
class database
{
    function __construct($dbhost, $user, $pass, $etc) { /* etc */ }
    function query($sql) { /* dowork*/ }
}
$args = array('localhost', 'user', 'pass', 'etc');

$db = create_object('database', $args); // is there a function like this?
$db->query('SELECT * FROM poop');
6
  • 1
    #include <database.h> ? Is this PHP or C here? Commented Feb 21, 2010 at 7:53
  • 1
    "#include" doesn't work the same way in PHP as in C or C++. You probably mean "include 'database.h';" or, better yet, "require_once 'database.h';" Commented Feb 21, 2010 at 7:54
  • You forgot a ' after etc;. Commented Feb 21, 2010 at 8:40
  • @Andrew Moore: you just concentrated on h part in my answer (even after i corrected it), did not look at rest of my answer and kept on reasoning, you do not seem to be a logical or gud guy, sorry for that :( Commented Feb 21, 2010 at 9:08
  • @Andrew Moore: sorry i was emotional probably, you are right, thanks :) Commented Feb 21, 2010 at 9:30

1 Answer 1

1

You can use ReflectionClass::newInstanceArgs for this:

class database
{
    function __construct($dbhost, $user, $pass, $etc) { /* etc */ }
    function query($sql) { /* dowork*/ }
}
$args = array('localhost', 'user', 'pass', 'etc');

$ref = new ReflectionClass('database');
$db = $ref->newInstanceArgs($args); 
Sign up to request clarification or add additional context in comments.

12 Comments

yes that good to use reflection class, but it fails if arguments are passed by referecne.
@Sarfraz: It wouldn't fail. In the example above, he is passing by value anyway... But if you want to pass by reference using the example above, you just need to make sure that a reference of your variable is inserted into $args instead of the variable itself. ($args = array($byValue, &$byReference);)
And if you have to automate this you can inspect the parameters of the constructor with ReflectionParameter::isPassedByReference()
@VolkerK: that's what i was expecting as an answer isPassedByReferece is the way to go :)
how it would fail can be found here: php.net/manual/en/reflectionclass.newinstanceargs.php. There i have provided a possible solution on how to avoid this problem, have a loot answer by sarfraznawaz2005
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.