Trying to understand parameters in classes

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
Jamie40
Forum Newbie
Posts: 4
Joined: Fri Nov 07, 2014 6:48 pm

Trying to understand parameters in classes

Post by Jamie40 »

I am going though the course right now on php and I am trying to understand the class structure. I understand that the __construct magic method runs first thing when your object is created. The class I am taking created a random generator to explain some concepts. what I don't understand is why declare $number outside of the construct when you could declare it inside or just make a function and declare it there?

Code: Select all

class Number {
	
	public $number;
	
	function __construct()
	{
		$this->number = rand(1, 10);
		echo $this->number;
		echo "<br />";
		ob_flush();
		flush();
		sleep(1);
		unset($this);
	}
	
	public function __destruct()
	{
		$number = new Number;
	}
}

$number = new Number;

I am guessing this is because variables declared inside a function are only available in that function and those declared outside are available to any function. Is this a correct understanding?
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Trying to understand parameters in classes

Post by twinedev »

Your guess is correct, If you created the variable inside __construct (or any other function) it would only be available inside that, not available for the whole class.

The example you are working on isn't a really good one to demonstrate this point. Where it is really noticeable is when you have more than one method (function) that uses the variable.

As a personal recommendation, for learning OOP with PHP, this is an awesome book: http://www.amazon.com/Objects-Patterns- ... 1430260319 I know lots of people like "free" resources, but this is one of the few where I say the $25 for the electronic version is well worth it. (myself, I use books24x7.com and read it there, if you are in school somewhere, see if their library services have access to it or something similar)
Jamie40
Forum Newbie
Posts: 4
Joined: Fri Nov 07, 2014 6:48 pm

Re: Trying to understand parameters in classes

Post by Jamie40 »

Thanks for the answer and the book information. I have a kindle, I will check it out.
Imran520
Forum Newbie
Posts: 2
Joined: Sat Nov 08, 2014 6:14 am

Re: Trying to understand parameters in classes

Post by Imran520 »

I understand it . it is very easy.
Post Reply