当前位置: 代码迷 >> PHP >> 一个对象怎么能new不成功
  详细解决方案

一个对象怎么能new不成功

热度:35   发布时间:2016-04-28 17:12:20.0
一个对象如何能new不成功
类似这样:


class MyClass {
  private $index;
  public function __construct($index) {
    if ($index === 0) {
      // 销毁对象
    }
    $this->index = $index;
  }

  public function getIndex() {
    return $this->index;
  }
}

$t = new MyClass(1);
echo $t->getIndex(); // 正确返回

$t = new MyCalss(0);
echo $t->getIndex(); // 失败。

------解决思路----------------------
为什么要这样?还是要单例模式?
------解决思路----------------------
把$t对象销毁了,就没有引用了
------解决思路----------------------
私有化构造函数
------解决思路----------------------
单例模式试试呗
  相关解决方案