mardi 4 août 2015

Global variable in object created from other object (PHP)

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 object, created from another object, can't declare vars as global, and use it?

P.S. Excuse my bad English.

Aucun commentaire:

Enregistrer un commentaire