简体   繁体   English

PHP有没有更好的缓存属性的方法?

[英]Is there a better way to cache a property in PHP?

I have an arbitrary number of classes already extending a base class, and I'd like for each of these extending classes to have a static function with the same name.我有任意数量的类已经扩展了一个基类 class,我希望每个扩展类都有一个同名的 static function。 This function is often very expensive and by nature should only need to be calculated once as its result will always be the same.这个 function 通常非常昂贵,本质上应该只需要计算一次,因为它的结果总是相同的。 Therefore I would like to cache it as a property if not already cached.因此,如果尚未缓存,我想将其缓存为属性。

The tricky thing I'm trying to achieve is to have this cache lazy-loaded, ie.我想要实现的棘手的事情是让这个缓存延迟加载,即。 only loaded if that static function is called.仅在调用 static function 时加载。 It's possible that only one of these classes will be used and I'd like to avoid having to cache all of them regardless of whether they're going to be used or not.有可能只会使用这些类中的一个,我想避免缓存所有这些类,无论它们是否会被使用。

What I currently have works, but I would like to know if there's a better way of doing this.我目前所做的工作,但我想知道是否有更好的方法来做到这一点。

<?php

echo Inside1::something() . "\n";
echo Inside2::something();

class Outside {

}

class Inside1 extends Outside {

    private static $name;

    public static function something(){
        if(!self::$name){
            self::$name = "Inside 1";
        }
        return self::$name;
    }
}

class Inside2 extends Outside {

    private static $name;

    public static function something(){
        if(!self::$name){
            self::$name = "Inside 2";
        }
        return self::$name;
    }

}

I usually go for something like this.对于这样的事情,我通常会拨打 go。

class Class
{
    /**
     * @return BothMethodsHaveTheSameReturnType $value
     */
    public property getValue(bool $shouldGetCachedValue = true)
    {
        static $value = null;

        $isValueAlreadyCached = null !== $value

        if (!shouldGetCachedValue || !isValueAlreadyCached) {
            $value = $this->heavyCalculation();
        }

        return $value;
    }

    /**
     * @return BothMethodsHaveTheSameReturnType $value
     */
    private function heavyCalculation()
    {
        # You gotta do what you gotta do!

        return $value;
    }
}

Note: If heavyCalculation returns null , it will recalculate on next call regardless of $shouldGetCachedValue parameter in getValue .注意:如果heavyCalculation返回null ,它将在下次调用时重新计算,而不管getValue中的$shouldGetCachedValue参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM