【问题标题】:Parse error: T_PAAMAYIM_NEKUDOTAYIM解析错误:T_PAAMAYIM_NEKUDOTAYIM
【发布时间】:2012-04-17 06:34:01
【问题描述】:

我在 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 [..]

我猜它与双点和静态函数有关,但我是这些类的新手,有什么问题?

【问题讨论】:

  • unexpected T_PAAMAYIM_NEKUDOTAYIM in ... 在哪里?你能突出显示指定的行吗?
  • 那里:if ( !$cache::is_cached('statistics') )
  • $this-&gt;easy_cache 定义在哪里?

标签: php parse-error


【解决方案1】:

您将实例调用与静态调用混合在一起。

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

应该是..

!$cache->is_cached();

与..相同。

$cache::store

您要么在对象的上下文中工作(使用 $this),要么执行静态调用(使用 ::)。你不能混合它们。

【讨论】:

  • 好的,谢谢,但是为什么我看到了很多我可以通过双点使用的类...为什么我不能在这里使用它们?
  • 双冒号(又名 Paamayim Nekudotayim)用于静态方法/属性。 “->” 用于其他所有内容。
  • 啊。他正在使用实例名称而不是类名称调用静态方法。即它应该是“Easy_cache::is_cached()”,正如 Frosty Z 下面所说的。
【解决方案2】:

您应该使用类名而不是类实例的静态调用 (::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 类应该像您尝试的那样使用,但是:

  • 使用-&gt; 代替:: 进行方法调用
  • 删除方法定义中的所有 static 关键字
  • (可选但推荐)将Easy_cache() 方法重命名为__construct()

【讨论】:

  • 谢谢你,你已经解释了这一切:)。你是对的,错误不是来自 CodeIgniter 代码库 - 编辑的标签。谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
  • 2013-12-15
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
相关资源
最近更新 更多