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条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?