我用兩個堆棧編寫了這個堆棧實現和部分實現隊列。除了一件事之外,幾乎所有事情都按預期工作對於某些問題,當我var_dump出隊的結果,它返回NULL,當我var_dump結果出隊內部它返回一個布爾值如預期。任何人都可以解釋從哪裏來的差異?PHP對象訪問問題
<?php
class stack
{
private $stack = array();
function push($value)
{
$this->stack[] = $value;
}
function pop()
{
if ($this->isEmpty())
throw new RunTimeException("Stack is empty");
$top = $this->stack[count($this->stack)-1];
unset($this->stack[count($this->stack)-1]);
$this->stack = array_values($this->stack);
return $top;
}
function isEmpty()
{
return empty($this->stack) ? true : false;
}
function peak()
{
$top = $this->stack[count($this->stack)];
return $top;
}
function printr()
{
print_r($this->stack);
}
}
class queue
{
function __construct()
{
$this->stack1 = new Stack();
$this->stack2 = new Stack();
}
function push($value)
{
$this->stack1->push($value);
}
function dequeue()
{
if (!$this->stack2->isEmpty())
{
$this->stack2->printr();
$pop = $this->stack2->pop();
var_dump($pop);
return $pop;
}
else if (!$this->stack1->isEmpty())
{
do
{
$pop = $this->stack1->pop();
$this->stack2->push($pop);
}
while ($this->stack1->isEmpty() === false);
$this->dequeue();
}
else
{
throw new RunTimeException("Queue is empty");
}
}
function isEmpty()
{
if (($this->stack1->isEmpty()) AND ($this->stack2->isEmpty()))
{
return true;
}
else
{
return false;
}
}
function peak()
{
}
}
$myQueue = new queue();
$myQueue->push(1);
$myQueue->push(2);
var_dump($myQueue->dequeue());
'?真:假 - 「你爲什麼這樣做?空已經返回一個布爾值 – ThiefMaster
你是完全正確的。對於那個很抱歉。 – user1029829