0

I have the following code in PHP. Testing in Phpunit and Laravel. Why is class method the same as instance method? I was expecting calling $instance->classMethod() would return some error. Does this also mean that instance method name shouldn't be shared by class method names? Or is 'static method' in php different from my understanding of a 'class method'?

<?php
class DemoClass{
    static function classMethod(){
        return "i'm a class method";
    }
}

class ExampleTest extends TestCase {

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $instance = new DemoClass;
        $result1 = $instance->classMethod();
        $result2 = DemoClass::classmethod();

        $this->assertNotEquals($result1, $result2);
    }

}

The result:

Failed asserting that 'i'm a class method' is not equal to <string:i'm a class method>.

randomor
  • 5,329
  • 4
  • 46
  • 68

1 Answers1

0

PHP is a very flexible language. There are many ways you can call static methods, 2 methods of which you have displayed above $object->staticmethod() or $object::staticMethod(). It is perfectly legal to call static methods from $this or the object instance.

Another way to call static/normal methods is using functions like call_user_func. An existing discussion exists over here:

Static methods in PHP

Community
  • 1
  • 1
Aziz Saleh
  • 2,687
  • 1
  • 17
  • 27
  • Thanks for pointing to the other question. I wasn't able to find it. I guess this is a feature, not a bug, for duck-typing class method mixed with instance method calling? Although a bit mind-bending from my previous OOP experience. – randomor Jun 01 '14 at 04:30