dsiy62758 2016-09-17 20:11
浏览 58
已采纳

为什么在实例化时调用PHP类方法?

Need some help understanding what's going on in my PHP code.

index.php

include("cache.php");
$cache = new Cache();

cache.php

class Cache {
    private static $URL_CACHE;

    public function cache($url, $entityId) {
        echo '<br>caching '.$url.' as '.$entityId;
    }

When I request index.php, I get 'caching as' displayed, which is a surprise. I never called $cache->cache('', '');

What's calling the method?


As per Blake's answer, since the method name matches (somewhat) the class name, it's called on instantiation. For Java developers this will certainly be a surprise.

  • 写回答

1条回答 默认 最新

  • duancong7358 2016-09-17 20:15
    关注

    This is using deprecated PHP functionality to act as a __contruct() method. In older versions of PHP (Removed in 7) If you had a class named Foo and a function named foo() it was how you would call it as a constructor.

    In short, this is being called by you instantiating the class. If you change your cache() method to makeCache() I bet it will go away.

    Another solution is to have an empty constructor as well, thanks JimL.

    public function __construct() {
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求