Constructor Variable Scope Help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dhui
Forum Newbie
Posts: 14
Joined: Mon May 10, 2010 1:42 pm

Constructor Variable Scope Help

Post by dhui »

How do I use variables declared in a class constructor in the other class functions?

Code: Select all

        function __construct()
	{
		include('../../classes/Obj.class.php'); 
		$Obj = new Obj;
		$Obj->connect();	
	}

	function getSomething()
	{	
               //use $Obj here
	}
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Constructor Variable Scope Help

Post by Weirdan »

By assigning them as a member of an object (via $this):

Code: Select all

include('../../classes/Obj.class.php'); 
class A {
        protected $obj = null;

        public function __construct()
        {   
                $this->obj = new Obj;
                $this->obj->connect();        
        }

        public function getSomething()
        {       
               //use $this->obj here
        }
}
dhui
Forum Newbie
Posts: 14
Joined: Mon May 10, 2010 1:42 pm

Re: Constructor Variable Scope Help

Post by dhui »

Thanks! Still getting used to php OOP variable scope and syntax :/
Post Reply