It is allowed, but you need to use the appropriate syntax: either the global
keyword or the $GLOBALS
superglobal:
http://es.php.net/manual/en/language.variables.scope.php
http://es.php.net/manual/en/reserved.variables.globals.php
<?php
class classname1{
private $id;
public function __construct($id){
$this->id = $id;
}
public function display(){
echo "Displaying " . $this->id . "...\n";
}
}
$newobj = new classname1(1);
class newclass {
public function test() {
global $newobj;
echo $newobj->display();
}
public function test_alt() {
echo $GLOBALS['newobj']->display();
}
}
$foo = new newclass;
$foo->test();
$foo->test_alt();
?>
However, global variables must always be used with caution. They can lead to code that's hard to understand and maintain and bugs that are hard to track down. It's normally easier to just pass the required arguments:
<?php
class classname1{
private $id;
public function __construct($id){
$this->id = $id;
}
public function display(){
echo "Displaying " . $this->id . "...\n";
}
}
$newobj = new classname1(1);
class newclass {
public function test(classname1 $newobj) {
echo $newobj->display();
}
}
$foo = new newclass;
$foo->test($newobj);
?>
Last but not least, you might be looking for the singleton OOP pattern:
http://en.wikipedia.org/wiki/Singleton_pattern