How to test if an instance is dynamic or static?

5

Let's say you access an object that you do not know how it was created and wants to know if it was instantiated as new \Acme\Foo() or if it was just returned \Acme\Foo ;

What is the most practical test? (removed the requirement "without using Reflection")

Example:

<?php

$foo = App::getService('foo');

App::getService() returned an object that is stored in $foo ;

$foo is a dynamic object?

    
asked by anonymous 21.07.2014 / 21:43

3 answers

3

It's quite simple! You can use is_object() :

<?php
class Foo {

    public function hello()
    {
        return 'world';
    }

    public static function hi()
    {
        return 'Joe';
    }
}

$foo = new Foo();
$bar = Foo;

var_dump($foo instanceof Foo);//true;
var_dump($bar instanceof Foo);//false
var_dump(is_object($foo)); //true
var_dump(is_object($bar)); //false

echo $foo->hello(); //world
echo $bar::hi();//Joe
    
22.07.2014 / 14:09
4

As far as I know, it is not possible to return a reference to a class in PHP without using Reflection. So the scenario where something would return \Acme\Foo , not an instance, would depend on Reflection. In any case, you can check if a variable contains an instance of a given class with the instanceof :

class Foo {

}
$foo = new Foo();
$fooEhInstancia = $foo instanceof Foo; // true

A live example (notice the notice in stderr)     

21.07.2014 / 23:17
2

See the example below:

<?php

class MyClass
{
  public function func1(){}
  public static function func2(){}
}

$reflection = new ReflectionClass('MyClass');

$func1 = $reflection->getMethod('func1');
$func2 = $reflection->getMethod('func2');

var_dump($func1->isStatic());
var_dump($func2->isStatic());

The methods of the MyClass class are tested. There are two, one static ( func2() ) and one dynamic ( func1() ). This code was taken from the link of the stackoverflow in English.

    
21.07.2014 / 22:01