I want to pass informations to a template:
public function do(array $p)
{
extract($p);
unset($p);
ob_start();
require('view.php');
return ob_get_clean();
}
$object->do([
'a' => 1
]);
view.php
<?php
var_dump(get_declared_vars());
this way the dump will output a => 1
and the $this
object, but I dont want to see $this
. How to nullify it?
From the manual
The pseudo-variable
$this
is available when a method is called from within an object context.$this
is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
This variable is added automatically and it's very useful when trying to access the classes variables from it's method.
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
Why this is bothering you, I don't know, but you can remove this by using:
$declared_vars = get_declared_vars();
unset($declared_vars["this"]);
var_dump($declared_vars);
(This is not tested because my php version doesn't have the get_declared_vars()
function, but if it returns an array, this is the path and may need only a few changes.
I tried this...
<?php
class forJohn {
public function test (array $p) {
extract($p);
unset( $p );
ob_start();
require( 'view.php' );
return ob_get_clean();
}
}
$object = new forJohn;
echo $object->test( ['a' => 1] );
View.php
<?php
var_dump(get_defined_vars());
Interestingly, this results in
array (size=1)
'a' => int 1
Now I have had to use get_defined_vars() as I don't have access to your get_declared_vars(). Might be that is the answer!