dongyuan4790
2013-11-04 07:51
浏览 21
已采纳

为什么PHP堆栈(我建立)没有工作?

i try to build stack in PHP, but its didnt work. why?

this is the problem that i see:

Warning: Missing argument 1 for object::object(), called in C:\Program Files (x86)\EasyPHP-12.1\www\tb\index.php on line 152 and defined in C:\Program Files (x86)\EasyPHP-12.1\www\tb\index.php on line 126

Notice: Undefined variable: txt in C:\Program Files (x86)\EasyPHP-12.1\www\tb\index.php on line 127

Fatal error: Call to undefined function back() in C:\Program Files (x86)\EasyPHP-12.1\www\tb\index.php on line 146

this is the code: (i wrote in the code the lines of the problem with // )

class object {
    private $obj;
    private $next = null;
    private $back = null;

    public function object($txt) {     // line 126
        $this->obj = $txt;     // line 127
    }
    public function back($back) {
        $this->back = $back;
    }
    public function next($next) {
        $this->next = $next;
    }
}

class stack2 extends object  {
    private $arr;
    private $head = -1;
    private $tail = 0;

    public function push($txt) {
        $this->head++;
        $arr[$this->head] = new object($txt);  
        if ($this->head-1 >= $this->tail) {  
            $arr[$this->head].back($this->head-1);     // line 146 
            $arr[$this->head-1].next($this->head); 
        }
    }
}

$s = new stack2();   // line 152
$s->push(11111);
$s->push(22222);
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dsnw2651 2013-11-04 07:53
    最佳回答

    Your object constructor defines one argument $txt to instanciate the class. In your class stack2 which inherts from object you must also write a constructor which calls its parent constructor with the needed parameter.

    class stack2 extends object {
      public function __construct() {
        $txt = 'your text here';
    
        parent::object($txt);
      }
    }
    

    And I would use the magic method __construct instead of a method with the same name as the class. Because if you refactor classes name you also have to refactor your constructor functions name.

    Your second error is that you call a method of an object with a . instead of ->. So the correct line would be:

    $arr[$this->head]->back($this->head-1);
    

    Than you want propably use the property $arr of your stack class so you have to use $this->arr instead of simply $arr in the example line above.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题