0

There are two classes, each one in its own file:

<?php
namespace test;

class calledClass {
    private $Variable;

    function __construct() {
        global $testVar;
        require_once 'config.php';
        $this->Variable = $testVar;
        echo "test var: ".$this->Variable;        
    }
}
?>

and

<?php
namespace test;

class callingClass {
    function __construct() {                
        require_once 'config.php';
        require_once 'calledClass.php';
        new calledClass();
    }
}

new callingClass();
?>

and simple config.php:

<?php
namespace test;
$testVar = 'there is a test content';
?>

When I start callingClass.php (which creates object calledClass), the property $Variable in calledClass is empty. But when I start calledClass.php manually, it reads meaning $testVar from config.php, and assumes it to $Variable.

If I declare $testVar as global in callingClass, it helps - calledClass can read $testVar from config.php.

Can somebody tell me why an object created from another object can't declare variables as global, and use them?

Ram
  • 3,092
  • 10
  • 40
  • 56
  • 2
    Besides the fact that this would be incredibly bad practise, and isn't OOP, and a myriad other issues with what you're doing; `$testVar` isn't global inside the callingClass constructor, just a locally scoped variable in that method – Mark Baker Aug 04 '15 at 11:31
  • Thank you. What is better way to use config file inside class (besides passing variables as functions' arguments)? `parse_ini_file`? – Volodymyr Pereguda Aug 05 '15 at 12:21

1 Answers1

0

When including (include/require) a file inside a function, all variable declarations inside that file get the scope of the function. So $testVar is created within the scope of callingClass::__construct. Since you use require_once, it will not be re-created elsewhere inside calledClass::__construct! It works when calling only calledClass since you're actually including the file for the first time there.

It has nothing to do with OOP at all, just the rules of function scope and your particular use of require_once.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Thanks for your explanation about `include/require`. But I need more help. When I add `print_r(get_included_files());` into calledClass in my example, it shows 'Array ( [0] => D:\htdocs\test\callingClass.php [1] => D:\htdocs\test\config.php [2] => D:\htdocs\test\calledClass.php ) '. That means config.php is included into calledClass. What interfere with reading variables fron included file inside `calledClass::__construct`? – Volodymyr Pereguda Aug 05 '15 at 12:12