rosengrenen
rosengrenen

Reputation: 781

PHP static vs. object calls

So I have this problem where I can call an object method statically and vice versa. Is this supposed to happen or what am I doing wrong in case?

PHP Version: 5.6.12 XAMPP Version: 3.2.1

function endl()
{
    echo "<br>";
}

class Base
{
    public function objectFunc($msg)
    {
        echo "You called a non-static function from " . $msg;
        endl();
    }

    public static function staticFunc($msg)
    {
        echo "You called a static function from " . $msg;
        endl();
        }
    }

Base::objectFunc("a static call");
Base::staticFunc("a static call");
$base = new Base;
$base->objectFunc("a non-static call");
$base->staticFunc("a non-static call");


Here are the results from running this:

You called a non-static function from a static call
You called a static function from a static call
You called a non-static function from a non-static call
You called a static function from a non-static call

Upvotes: 1

Views: 76

Answers (2)

jkon
jkon

Reputation: 191

If you put:

error_reporting(E_ALL);
ini_set('display_errors', '1');

in PHP 7.0 you will have the message: Deprecated: Non-static method Base::objectFunc() should not be called statically in ...

But notice that it is not an error but a “deprecated” warning. Also no errors or warnings come out of:

$base->staticFunc("a non-static call");

This is an old known issue in PHP . (It has to do of how PHP was in PHP 4 and moving to PHP 5 decided to have backwards compatibility )

Probably because this behavior is many years around it hasn't been altered even in PHP 7 allhtough it is irrational and allow very bad programming habits. You are correct there is something terrible wrong about it. That PHP allows it , doesn't mean that anyone that don't like to endorse bad programming habits should programming that way.

Upvotes: 0

Pikdo
Pikdo

Reputation: 26

This could help you:

"Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can)" by php.net

"Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

Caution: In PHP 5, calling non-static methods statically generates an E_STRICT level warning.

Warning: In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future. " by php.net

Your code is going to work but with warnings, it depends of php version.

For more see: http://php.net/manual/en/language.oop5.static.php

Upvotes: 1

Related Questions