Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "invoke" a class instance in PHP?

is there any possibility to "invoke" a class instance by a string representation?

In this case i would expect code to look like this:

class MyClass {
  public $attribute;
}

$obj = getInstanceOf( "MyClass"); //$obj is now an instance of MyClass
$obj->attribute = "Hello World";

I think this must be possible, as PHP's SoapClient accepts a list of classMappings which is used to map a WSDL element to a PHP Class. But how is the SoapClient "invoking" the class instances?

like image 791
NovumCoder Avatar asked Oct 09 '09 09:10

NovumCoder


People also ask

How do I instance a class in PHP?

new ¶ To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

How do you call a class in PHP?

PHP: Class Constants When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).

What is __ invoke in PHP?

__invoke() ¶ The __invoke() method is called when a script tries to call an object as a function. Example #4 Using __invoke() class CallableClass. { public function __invoke($x)

What is the right way to invoke a method in PHP?

To invoke a method on an object, you simply call the object name followed by "->" and then call the method. Since it's a statement, you close it with a semicolon. When you are dealing with objects in PHP, the "->" is almost always used to access that object, whether it's a property or to call a method.


2 Answers

$class = 'MyClass';
$instance = new $class;

However, if your class' constructor accepts a variable number of arguments, and you hold those arguments in an array (sort of call_user_func_array), you have to use reflection:

$class = new ReflectionClass('MyClass');
$args  = array('foo', 'bar');
$instance = $class->newInstanceArgs($args);

There is also ReflectionClass::newInstance, but it does the same thing as the first option above.

Reference:

  • Object instantiation
  • ReflectionClass::newInstanceArgs()
  • ReflectionClass::newInstance()
like image 156
Ionuț G. Stan Avatar answered Oct 25 '22 04:10

Ionuț G. Stan


The other answers will work in PHP <= 5.5, but this task gets a lot easier in PHP 5.6 where you don't even have to use reflection. Just do:

<?php

class MyClass
{
    public function __construct($var1, $var2)
    {}
}

$class = "MyClass";
$args = ['someValue', 'someOtherValue'];

// Here's the magic
$instance = new $class(...$args);
like image 38
Lars Nyström Avatar answered Oct 25 '22 06:10

Lars Nyström