Reputation: 78991
Here is the situation I create a instance of a class
$newobj = new classname1;
Then I have another class writtern below and I want to this class to access the object above
class newclass {
public function test() {
echo $newobj->display();
}
}
It is not allowed, is there a way define a variable globally through a class?
Upvotes: 0
Views: 173
Reputation: 704
Could look at using the singleton pattern. This basically is a class that creates an instance of itself and subsequent calls will access this instance and therefore achieving what I think you might be up to...
Upvotes: 0
Reputation: 22438
Make the instance a global:
$newobj = new classname1;
class newclass {
public function test() {
global $newobj;
echo $newobj->display();
}
}
Since I got a downvote for the first line, I removed it.
Upvotes: 1
Reputation: 146460
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
Upvotes: 6
Reputation: 2848
you can also inherit your newclass from classname1 and then you will be able to call the methods of the class 'classname1' like this:
class newclass extends classname1 {
public function test() {
echo parent::display();
}
}
Upvotes: 0