簡體   English   中英

解析錯誤:T_PAAMAYIM_NEKUDOTAYIM

[英]Parse error: T_PAAMAYIM_NEKUDOTAYIM

我在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');
    }

}

我現在想使用它,因此在控制器中,我正在使用它(我通過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()));
    }
}

然后我得到這個錯誤:

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

我猜它與雙點和靜態函數有關,但是我是此類的新手,那么問題出在哪里呢?

您將實例調用與靜態調用混合在一起。

$cache = $this->easy_cache;
!$cache::is_cached

應該..

!$cache->is_cached();

與...相同

$cache::store

您要么在對象的上下文中工作(使用$ this),要么執行靜態調用(使用::)。 你不能混合他們。

您應該使用帶有類名而不是類實例的靜態調用( ::someMethod() )。

由於Easy_cache所有方法都是靜態的,因此您應該

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

代替

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

順便說一句,您確定這來自CodeIgniter代碼庫嗎? 這混合了靜態和動態上下文:

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

IMO,應該像您嘗試的那樣使用Easy_cache類,但是:

  • 使用->代替::進行方法調用
  • 刪除方法定義中的所有static關鍵字
  • (可選,但建議使用)將Easy_cache()方法重命名為__construct()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM