Recommended replacement for LimitedScope in Nette 2.2

Notice: This thread is very old.
mystik
Member | 308
+
0
-

What is recommended replacement for LimitedScope which is deprecated in Nette 2.2?

Let's say I have this code:

<?php
  ob_start();
  Nette\Utils\LimitedScope::load($file, $vars);
  return ob_get_clean();
?>

What should I use instead? Just this:

<?php
  ob_start();
  extract($vars);
  include($file);
  return ob_get_clean();
?>

Last edited by mystik (2014-05-15 09:45)

Milo
Nette Core | 1283
+
0
-

You can:

$vars = array(...);
$output = call_user_func(function() {
	ob_start();
	if (func_num_args() > 1) {
		extract(func_get_arg(1));
	}
	require func_get_arg(0);
	return ob_get_clean();
}, $file, $vars);
mystik
Member | 308
+
0
-

Thanks. Exactly what I was looking for.

I was recommended elsewhere not to use extract. So my final solution looks like:

<?php
return call_user_func(function() {
  ob_start();
  foreach (func_get_arg(1) as $__k => $__v) {
    $$__k = $__v;
  }
  unset($__k, $__v);
  require func_get_arg(0);
  return ob_get_clean();
}, $file, $vars);
?>
Milo
Nette Core | 1283
+
0
-

extract() is slower but only for bigger amount of variables.

Jan Tvrdík
Nette guru | 2595
+
0
-

extract() is slower but only for bigger amount of variables.

and older versions of PHP.

mishak
Member | 94
+
0
-

You can test it :)