views:

70

answers:

4

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?

+1  A: 

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.

Harmen
no need for the first global. the global keyword will only work in functions
knittl
A: 

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...

Simon Thompson
+6  A: 

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

Álvaro G. Vicario
A: 

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();
    }
}

Gaurav Sharma