duanjia3187 2016-01-21 16:34
浏览 40
已采纳

PHP静态与对象调用

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
  • 写回答

2条回答 默认 最新

  • 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 SQL server表计算问题
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出