Search code examples
phpparse-error

Parse error: T_PAAMAYIM_NEKUDOTAYIM


I got this simple cache class setted up as a library in the Codeigniter:

<?php

class Easy_cache {

    static public $expire_after;

    static function Easy_cache()
    {
        if ($this->expire_after == '')
        {
             $this->expire_after = 300;
        }
    }

    static function store($key, $value)
    {
        $key = sha1($key);
        $value = serialize($value);
        file_put_contents(BASEPATH.'cache/'.$key.'.cache', $value);
    }

    static function is_cached($key)
    {
        $key = sha1($key);
        if (file_exists(BASEPATH.'cache/'.$key.'.cache') && (filectime(BASEPATH.'cache/'.$key.'.php')+$this->expire_after) >= time())
            return true;

        return false;
    }

    static function get($key)
    {
        $key = sha1($key);
        $item = file_get_contents(BASEPATH.'cache/'.$key.'.cache');
        $items = unserialize($item);

        return $items;
    }

    static function delete($key)
    {
        unlink(BASEPATH.'cache/'.sha1($key).'.cache');
    }

}

I want to use it now, so in the controller I'm using this (I'm loading the library via autoload.php):

class Main extends CI_Controller
{
    public function __construct()
    {

        parent::__construct();
    }

    public function index()
    {
        $cache = $this->easy_cache;
        if ( !$cache::is_cached('statistics') )
        {
            $data = array('data' => $this->model_acc->count());
            $cache::store('server_statistics', $data);
        }
        else
            $data = array('this' => 'value');

        $this->load->view('main', array('servers' => $this->servers->get()));
    }
}

And then I'm getting this error:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in [..]

I guess its something related to the double dots and the static function, but I'm a newbie with the classes, so whats the problem?


Solution

  • You should use statics calls (::someMethod()) with the class name, not a class instance.

    Since all methods of Easy_cache are static, you should do

    Easy_cache::is_cached()
    Easy_cache::store()
    

    instead of

    $cache::is_cached()
    $cache::store()
    

    BTW, are you sure that this comes from CodeIgniter codebase? This mixes static and dynamic context:

    static function Easy_cache()
    {
        if ($this->expire_after == '')
        {
             $this->expire_after = 300;
        }
    }
    

    IMO, class Easy_cache should be used like you tried to, but:

    • use -> instead of :: for method calls
    • remove all static keywords in the methods definitions
    • (optional but recommended) rename Easy_cache() method to __construct()