简体   繁体   中英

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. This function is often very expensive and by nature should only need to be calculated once as its result will always be the same. 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. 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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