我们可以获得ob级别。我们可以得到当前ob堆栈的长度。但是我们可以在n级别引用ob堆栈吗?若能得到特定深度的缓冲区长度,我会受益匪浅。
假设一个例子:
$length = array();
ob_start();
echo "1";
$length[] = ob_get_length(); // length of current stack (depth 1) is 1
ob_end_clean();
ob_start();
echo "11";
ob_start();
echo "2";
$length[] = ob_get_length(); // length of current stack (depth 2) is 1
ob_end_clean();
ob_end_clean();
ob_start();
echo "111";
ob_start();
echo "22";
ob_start();
echo "3";
$length[] = ob_get_length(); // length of current stack (depth 3) is 1
ob_end_clean();
ob_end_clean();
ob_end_clean();
print_r($length);
输出为:
Array
(
[0] => 1
[1] => 1
[2] => 1
)
每个最深堆栈的长度为1。这是意料之中的事。
我的应用程序有递归输出生成,一些输出堆栈必须知道父系统生成堆栈的长度。我不能仅仅依靠在打开新堆栈之前使用ob_get_length()
,因为其他人可以将生成器封装在自己的ob堆栈中。这将破坏应用程序。
有什么选择吗?谢谢
编辑:
为了说明我需要得到什么:
ob_start();
echo "111"; // <-- this is the stack of interest
ob_start();
echo "22";
ob_start();
echo "3";
$length[] = ob_get_length(); // length of current stack (depth 3) is 1
$top_stack_len = get_length_of_ob_stack(1); // expected length here should be 3 (strlen("111") == 3)
ob_end_clean();
ob_end_clean();
echo "some more chars to change length of stack 1";
ob_end_clean();
echo $top_stack_len; // I'm expecting to see 3 here.
更新:
你可以创建一个类来处理它。我相信这节课就足够了,如果你需要进一步的帮助,请告诉我。
class Ob {
static protected $_level = 0;
static protected $_data = array();
static function start() {
ob_flush();
self::$_level++;
ob_start("Ob::store");
}
static function end() {
ob_end_flush();
self::$_level--;
}
static function length($level) {
ob_flush();
return strlen(self::$_data[$level]);
}
static function store() {
if(self::$_level != 0)
self::$_data[self::$_level] .= ob_get_contents();
}
static function printData() {
print_r(self::$_data);
}
}
示例:
Ob::start();
echo '1';
Ob::start();
echo '2222';
Ob::start();
echo '2';
echo Ob::length(1);
echo Ob::length(2);
echo Ob::length(3);
Ob::end();
echo Ob::length(1);
echo Ob::length(2);
echo Ob::length(3);
Ob::end();
echo Ob::length(1);
echo Ob::length(2);
echo Ob::length(3);
Ob::end();
echo Ob::length(1);
echo Ob::length(2);
echo Ob::length(3);
Ob::printData();