How do you make a class property available to the other included file inside the same class method?
// file A.php
class A
{
private $var = 1;
public function go()
{
include( another.php );
}
}
in another file:
// this is another.php file
// how can I access class A->var?
echo $var; // this can t be right
Is this possible given the scope. If var is an array then we can use extract but if var is not, we can wrap it in an array. Is there a better way ?
Thanks!
EDIT
okay, to clarify another.php is literally another file. Basically, in the above examples, we have 2 files A.php which contains class A and another.php which is another file/script executing something.
Answered: My bad... I included another.php from index.php.. I see scoping still applies.. thanks everyone..
Your question seems to be, " when inside a file included from within a method, how do I access a private instance member? " Right?
In your example code, you re including a file inside a method.
Methods are just functions. Like all other areas of PHP, the file that gets included will inherit the entire current scope . That means that the include sees everything in scope in that method. Including $this.
In other words, you d access the property in the include file just like you d access it from inside the function itself, as $this->var.
Example, using the PHP interactive shell:
[charles@lobotomy /tmp]$ cat test.php
<?php
echo $this->var, "
";
[charles@lobotomy /tmp]$ php -a
Interactive shell
php > class Test2 { private $var; public function __construct($x) { $this->var = $x; } public function go() { include ./test.php ; } }
php > $t = new Test2( Hello, world! );
php > $t->go();
Hello, world!
php > exit
[charles@lobotomy /tmp]$ php --version
PHP 5.4.4 (cli) (built: Jun 14 2012 18:31:18)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
with Xdebug v2.2.0rc1, Copyright (c) 2002-2012, by Derick Rethans
http://stackoverflow.com/questions/13774669/access-property-from-include-inside-a-class-method-in-php