Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 180
  • Last Modified:

object is the same as className

<?php
class HelloWorld{
  public function sayHelloTo($name){
    return 'Hello '.$name;
  }
}

$obj=new HelloWorld();
//$reflectionMethod=new ReflectionMethod('HelloWorld','sayHelloTo');
$reflectionMethod=new ReflectionMethod($obj,'sayHelloTo');
echo $reflectionMethod->invoke(new HelloWorld(),'Mike');

Open in new window


please explain why
//$reflectionMethod=new ReflectionMethod('HelloWorld','sayHelloTo');
$reflectionMethod=new ReflectionMethod($obj,'sayHelloTo');

are the same
0
rgb192
Asked:
rgb192
  • 3
  • 2
1 Solution
 
Julian HansenCommented:
The answer is in the documentation for ReflectionMethod
http://www.php.net/manual/en/reflectionmethod.construct.php
 class
    Classname or object (instance of the class) that contains the method.

Open in new window

In other words the constructor for the Reflection method can take either

- The name of a class
OR
- An already instantiated (object) instance of a class
The commented out line above does the former - it passes the class name in as a string. The ReflectionMethod constructor recognises it is a string and will automatically create an object of that class type.
If it is an object (as in the second line) then it will simply use that object.
0
 
rgb192Author Commented:
Ok so in all the examples of php: is 'className' same as $obj?
Or is the reflection documentation saying it will take either
0
 
Julian HansenCommented:
Ok so in all the examples of php: is 'className' same as $obj?
No definitely not
What the code is doing is probably something like this
public ReflectionMethod::__construct ( mixed $class , string $name )
{
    // CHECK IF $class IS AN OBJECT
    if (!is_object($class)) {
       // IF NOT CHECK IF A CLASS EXISTS WITH NAME $class
       if (class_exists($class)) {
          // IF SO INSTANTIATE IT
          $obj = new {$class};
       }
       else {
          //THROW AN ERROR HERE - class not found
       }
    }
    // IF $class IS AN OBJECT THEN JUST ASSIGN IT
    else {
       $obj = $class;
    }
}

Open in new window

The above is just an illustration - I cannot confirm if the actual code follows this pattern. The point being that in PHP there is a distinction between a class name and an instance of the class - you cannot use them interchangeably.
0
 
rgb192Author Commented:
Thanks for example of what is in reflection class
0
 
Julian HansenCommented:
You are welcome - thanks for the points.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now