dsiy62758 2016-09-17 12: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 12: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() {
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?