I want to use a variable (string value) to call a Class. Can I do it ? I search for PHP ReflectionClass but I do not know how to use a method from Reflection Result. Like this:
foreach($menuTypes as $key => $type){
if($key != 'Link'){
$class = new \ReflectionClass('\App\Models\\' . $key);
//Now $class is a ReflectionClass Object
//Example: $key now is "Product"
//I'm fail here and cannot call the method get() of
//the class Product
$data[strtolower($key) . '._items'] = $class->get();
}
}
Without ReflectionClass:
$instance = new $className();
With ReflectionClass: use the ReflectionClass::newInstance() method:
$instance = (new \ReflectionClass($className))->newInstance();
I found one like this
$str = "ClassName";
$class = $str;
$object = new $class();
You can use directly like below
$class = new $key();
$data[strtolower($key) . '._items'] = $class->get();
The risk is that the class doesn't exist. So it's better to check before instantiating.
With php's class_exists method
Php has a built-in method to check if the class exists.
$className = 'Foo';
if (!class_exists($className)) {
throw new Exception('Class does not exist');
}
$foo = new $className;
With try/catch with rethrow
A nice approach is trying and catching if it goes wrong.
$className = 'Foo';
try {
$foo = new $className;
}
catch (Exception $e) {
throw new MyClassNotFoundException($e);
}
$foo->bar();
Related
I have two classes, class ClassOne { } and class ClassTwo {}. I am getting a string which can be either "One" or "Two".
Instead of using a long switch statement such as:
switch ($str) {
case "One":
return new ClassOne();
case "Two":
return new ClassTwo();
}
Is there a way I can create an instance using a string, i.e. new Class("Class" . $str);?
Yes, you can!
$str = 'One';
$class = 'Class'.$str;
$object = new $class();
When using namespaces, supply the fully qualified name:
$class = '\Foo\Bar\MyClass';
$instance = new $class();
Other cool stuff you can do in php are:
Variable variables:
$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123
And variable functions & methods.
$func = 'my_function';
$func('param1'); // calls my_function('param1');
$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method.
You can simply use the following syntax to create a new class (this is handy if you're creating a factory):
$className = $whatever;
$object = new $className;
As an (exceptionally crude) example factory method:
public function &factory($className) {
require_once($className . '.php');
if(class_exists($className)) return new $className;
die('Cannot create new "' . $className . '" class - includes not found or class unavailable.');
}
have a look at example 3 from http://www.php.net/manual/en/language.oop5.basic.php
$className = 'Foo';
$instance = new $className(); // Foo()
Lets say ClassOne is defined as:
public class ClassOne
{
protected $arg1;
protected $arg2;
//Contructor
public function __construct($arg1, $arg2)
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function echoArgOne
{
echo $this->arg1;
}
}
Using PHP Reflection;
$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);
Create a new Instance:
$instance = $class->newInstanceArgs(["Banana", "Apple")]);
Call a method:
$instance->echoArgOne();
//prints "Banana"
Use a variable as a method:
$method = "echoArgOne";
$instance->$method();
//prints "Banana"
Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)
// Way #1
$className = "App\MyClass";
$instance = new $className();
// Way #2
$className = "App\MyClass";
$class = new \ReflectionClass($className);
// Create a new Instance without arguments:
$instance = $class->newInstance();
// Create a new Instance with arguments (need a contructor):
$instance = $class->newInstanceArgs(["Banana", "Apple"]);
I have two classes, class ClassOne { } and class ClassTwo {}. I am getting a string which can be either "One" or "Two".
Instead of using a long switch statement such as:
switch ($str) {
case "One":
return new ClassOne();
case "Two":
return new ClassTwo();
}
Is there a way I can create an instance using a string, i.e. new Class("Class" . $str);?
Yes, you can!
$str = 'One';
$class = 'Class'.$str;
$object = new $class();
When using namespaces, supply the fully qualified name:
$class = '\Foo\Bar\MyClass';
$instance = new $class();
Other cool stuff you can do in php are:
Variable variables:
$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123
And variable functions & methods.
$func = 'my_function';
$func('param1'); // calls my_function('param1');
$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method.
You can simply use the following syntax to create a new class (this is handy if you're creating a factory):
$className = $whatever;
$object = new $className;
As an (exceptionally crude) example factory method:
public function &factory($className) {
require_once($className . '.php');
if(class_exists($className)) return new $className;
die('Cannot create new "' . $className . '" class - includes not found or class unavailable.');
}
have a look at example 3 from http://www.php.net/manual/en/language.oop5.basic.php
$className = 'Foo';
$instance = new $className(); // Foo()
Lets say ClassOne is defined as:
public class ClassOne
{
protected $arg1;
protected $arg2;
//Contructor
public function __construct($arg1, $arg2)
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function echoArgOne
{
echo $this->arg1;
}
}
Using PHP Reflection;
$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);
Create a new Instance:
$instance = $class->newInstanceArgs(["Banana", "Apple")]);
Call a method:
$instance->echoArgOne();
//prints "Banana"
Use a variable as a method:
$method = "echoArgOne";
$instance->$method();
//prints "Banana"
Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)
// Way #1
$className = "App\MyClass";
$instance = new $className();
// Way #2
$className = "App\MyClass";
$class = new \ReflectionClass($className);
// Create a new Instance without arguments:
$instance = $class->newInstance();
// Create a new Instance with arguments (need a contructor):
$instance = $class->newInstanceArgs(["Banana", "Apple"]);
I have a custom PHP class with few methods in it. Is is possible to call class method this way:
<?php
class someClass{
function someMethod_somename_1(){
echo 'somename1';
}
function someMethod_somename_2(){
echo 'somename2';
}
}
$obj = new someClass();
$methodName = $_GET['method_name'];
$obj->someMethod_{$methodName}(); //calling method
?>
My real world application is more complex, but here I provide just this simple example to get the main idea. Maybe I can use eval function here?
Please don't use eval() because it's evil in most situations.
Simple string concatenation helps you:
$obj->{'someMethod_'.$methodName}();
You should also verify the user input!
$allowedMethodNames = array('someone_2', 'someone_1');
if (!in_array($methodName, $allowedMethodNames)) {
// ERROR!
}
// Unrestricted access but don't call a non-existing method!
$reflClass = new ReflectionClass($obj);
if (!in_array('someMethod_'.$methodName, $reflClass->getMethods())) {
// ERROR!
}
// You can also do this
$reflClass = new ReflectionClass($obj);
try {
$reflClass->getMethod('someMethod_'.$methodName);
}
catch (ReflectionException $e) {
// ERROR!
}
// You can also do this as others have mentioned
call_user_func(array($obj, 'someMethod_'.$methodName));
Of course, take this:
$obj = new someClass();
$_GET['method_name'] = "somename_2";
$methodName = "someMethod_" . $_GET['method_name'];
//syntax 1
$obj->$methodName();
//alternatively, syntax 2
call_user_func(array($obj, $methodName));
Concatenate the whole method name before you call it.
Update:
Directly calling methods based on user input is never a good idea. Consider doing some previous validation of the method name before.
You may also take advantage of php magic methods, namely __call() in combination with call_user_func_array() and method_exists():
class someClass{
public function __call($method, $args) {
$fullMethod = 'someMethod_' . $method;
$callback = array( $this, $fullMethod);
if( method_exists( $this, $fullMethod)){
return call_user_func_array( $callback, $args);
}
throw new Exception('Wrong method');
}
// ...
}
For safety purposes you may want to create a wrapper which would prohibit calling other methods, like this:
class CallWrapper {
protected $_object = null;
public function __construct($object){
$this->_object = $object;
}
public function __call($method, $args) {
$fullMethod = 'someMethod_' . $method;
$callback = array( $this->_object, $fullMethod);
if( method_exists( $this->_object, $fullMethod)){
return call_user_func_array( $callback, $args);
}
throw new Exception('Wrong method');
}
}
And use it as:
$call = new CallWrapper( $obj);
$call->{$_GET['method_name']}(...);
Or maybe create execute method and than add to someClass method GetCallWrapper().
This way you'll get functionality well encapsulated into objects (classes) and won't have to copy it every time (this may come in handy if you'll need to apply some restrictions, i.e. privileges checking).
It is possible to use variable as function.
For example if you have function foo() you can have some variable $func and call it. Here is example:
function foo() {
echo "foo";
}
$func = 'foo';
$func();
So it should work like $obj->$func();
I have two classes, class ClassOne { } and class ClassTwo {}. I am getting a string which can be either "One" or "Two".
Instead of using a long switch statement such as:
switch ($str) {
case "One":
return new ClassOne();
case "Two":
return new ClassTwo();
}
Is there a way I can create an instance using a string, i.e. new Class("Class" . $str);?
Yes, you can!
$str = 'One';
$class = 'Class'.$str;
$object = new $class();
When using namespaces, supply the fully qualified name:
$class = '\Foo\Bar\MyClass';
$instance = new $class();
Other cool stuff you can do in php are:
Variable variables:
$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123
And variable functions & methods.
$func = 'my_function';
$func('param1'); // calls my_function('param1');
$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method.
You can simply use the following syntax to create a new class (this is handy if you're creating a factory):
$className = $whatever;
$object = new $className;
As an (exceptionally crude) example factory method:
public function &factory($className) {
require_once($className . '.php');
if(class_exists($className)) return new $className;
die('Cannot create new "' . $className . '" class - includes not found or class unavailable.');
}
have a look at example 3 from http://www.php.net/manual/en/language.oop5.basic.php
$className = 'Foo';
$instance = new $className(); // Foo()
Lets say ClassOne is defined as:
public class ClassOne
{
protected $arg1;
protected $arg2;
//Contructor
public function __construct($arg1, $arg2)
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function echoArgOne
{
echo $this->arg1;
}
}
Using PHP Reflection;
$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);
Create a new Instance:
$instance = $class->newInstanceArgs(["Banana", "Apple")]);
Call a method:
$instance->echoArgOne();
//prints "Banana"
Use a variable as a method:
$method = "echoArgOne";
$instance->$method();
//prints "Banana"
Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)
// Way #1
$className = "App\MyClass";
$instance = new $className();
// Way #2
$className = "App\MyClass";
$class = new \ReflectionClass($className);
// Create a new Instance without arguments:
$instance = $class->newInstance();
// Create a new Instance with arguments (need a contructor):
$instance = $class->newInstanceArgs(["Banana", "Apple"]);
I have two classes:
class Test {
public $name;
}
/*******/
class MyClass {
private $_test = NULL;
__get($name)
{
return $this->$name;
}
__set($name,$value)
{
$this->$name = $value;
}
}
And when I want to use it this way:
$obj1 = new MyClass();
$obj1->_test = new Test();
$obj1->_test->name = 'Test!';
Everything is ok. But it is also possible, that someone might use it this way:
$obj1 = new MyClass();
$obj1->_test->name = 'Test!';
Then I get notice "Notice: Indirect modification of overloaded property MyClass::$_test has no effect in /not_important_path_here". Instead that notice I want to throw an Exception. How to do it?
What you're looking for is the ErrorException object.
function exception_error_handler($no, $str, $file, $line ) { throw new ErrorException($str, 0, $no, $file, $line); }
set_error_handler("exception_error_handler");
In your __get() method check to see if $_test is an instance of Test. If it is return it, otherwise throw the exception in the __get() method.