2016-01-21 16:34
浏览 40


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;

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

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
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtz30833
    dtz30833 2016-01-21 16:56

    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

    点赞 评论
  • dshw124502
    dshw124502 2016-01-21 19:27

    If you put:

    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.

    点赞 评论