【问题标题】:Yii CList error - do not have a method or closure named "setReadOnly"Yii CList 错误 - 没有名为“setReadOnly”的方法或闭包
【发布时间】:2014-02-28 16:24:19
【问题描述】:

我有一个使用 CList 的基本函数 - 出于某种原因,我收到以下错误:

CList and its behaviors do not have a method or closure named "setReadOnly".

我的php代码

$list = new CList(array('python', 'ruby'));
$anotherList = new Clist(array('php'));
    var_dump($list);
$list->mergeWith($anotherList);
    var_dump($list);
$list->setReadOnly(true); // CList and its behaviors do not have a method or closure named "setReadOnly". 

谁能解释我为什么会收到这个错误?

P.S 我直接从最近的一本 Yii 书中复制了这段代码......所以我有点困惑

// 更新:在mergeWith()前后添加了var_dump

object(CList)[20]
  private '_d' => 
    array (size=2)
     0 => string 'python' (length=6)
     1 => string 'ruby' (length=4)
  private '_c' => int 2
  private '_r' => boolean false
  private '_e' (CComponent) => null
  private '_m' (CComponent) => null

object(CList)[20]
  private '_d' => 
    array (size=3)
    0 => string 'python' (length=6)
    1 => string 'ruby' (length=4)
    2 => string 'php' (length=3)
  private '_c' => int 3
  private '_r' => boolean false
  private '_e' (CComponent) => null
  private '_m' (CComponent) => null

【问题讨论】:

  • 你试过 print_r($list);检查 clist 是否具有只读变量。在合并之前和之后执行 print_r。
  • 我在调用 mergeWith() 函数之前和之后添加了列表变量的 var_dump
  • readonly 是公共成员但继承。反正问题很奇怪。
  • 这很奇怪..这并不重要我只是在 Yii 中玩一些“较小”的功能我还没有遇到过......但是我同意这很奇怪:)

标签: yii frameworks clist


【解决方案1】:

CList 方法 setReadOnly() 是受保护的,因此不能从您正在使用的范围内调用,只能从其自身或继承类中调用。见http://php.net/manual/en/language.oop5.visibility.php#example-188

但是,CList 类允许在其构造函数中将列表设置为只读

public function __construct($data=null,$readOnly=false)
{
    if($data!==null)
    $this->copyFrom($data);
    $this->setReadOnly($readOnly);
}

所以...

$list = new CList(array('python', 'ruby'), true); // Passing true into the constructor
$anotherList = new CList(array('php'));
$list->mergeWith($anotherList);

导致错误

CException The list is read only. 

我不确定这是否是您正在寻找的结果,但如果您想要一个只读的 CList,这是获得它的一种方法。

你可能认为在合并后续 CList 时可以在最后设置 readonly true,但是 mergeWith() 只合并 _d 数据数组,而不是其他类变量,所以它仍然为 false。

$list = new CList(array('python', 'ruby'));
$anotherList = new CList(array('php'));
$yetAnotherList = new CList(array('javacript'), true);

$list->mergeWith($anotherList);
$list->mergeWith($yetAnotherList);

var_dump($list); // ["_r":"CList":private]=>bool(false)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    相关资源
    最近更新 更多