Я написал эту реализацию стека и частичную реализацию очереди с использованием двух стеков. Почти все работает как ожидалось, кроме одного. Для некоторой проблемы, когда я var_dump результат dequeue, он возвращает NULL, когда, когда я var_dump результат внутри dequeue, он возвращает логическое значение, как ожидалось. Может ли кто-нибудь объяснить, в чем разница?Проблема доступа к объекту 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());
'? true: false' - зачем вы это делаете? empty уже возвращает boolean – ThiefMaster
Вы совершенно правы. Извини за это. – user1029829