Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, why I am able to access non-static method in a static way?

Tags:

php

static

In the following code, nonStatic() is not a static method. Even then I am able to access it without creating an object (in a static way). Could anyone please help me in understanding as this is not possible in other languages like Java?

<?php
class MyClass
{
    function nonStatic() {
        echo "This can be printed";
    }
}
MyClass::nonStatic(); // This can be printed
like image 442
Veeshoo Avatar asked May 01 '12 02:05

Veeshoo


2 Answers

It's allowed, but it generates an E_STRICT warning:

Error #: 2048, Error: Non-static method MyClass::nonStatic() should not be called statically, assuming $this from incompatible context

In the earlier OO implementations of PHP this was silently allowed, but better practices have since been adopted.

The opposite works without a hitch though:

class Test
{
    function foo()
    {
        echo $this->bar();
    }

    static function bar()
    {
        return "Hello world\n";
    }
}

$x = new Test;
$x->foo();

This prints Hello world.

like image 100
Ja͢ck Avatar answered Sep 28 '22 08:09

Ja͢ck


It seems as though the developers of PHP didn't see any value in disallowing static access of non-static methods. This is just one of those idiosyncratic features of PHP that doesn't really serve a purpose. It certainly is bad programming practice to call a non-static method statically, but in PHP it is possible. Maybe in a future version of PHP they will disallow this, but for now, it's just part of the language.

Edit:

Thankfully, the opposite is not allowed - you cannot call a static method from an object context. As Jack pointed out below, you can call a static method from an object context - hardly a best practice in the OOP paradigm, but it's allowed.

like image 30
Andrew Avatar answered Sep 28 '22 08:09

Andrew