Page 1 of 1

Trying to understand parameters in classes

Posted: Fri Nov 07, 2014 6:54 pm
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?

Re: Trying to understand parameters in classes

Posted: Fri Nov 07, 2014 7:35 pm
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)

Re: Trying to understand parameters in classes

Posted: Fri Nov 07, 2014 7:39 pm
by Jamie40
Thanks for the answer and the book information. I have a kindle, I will check it out.

Re: Trying to understand parameters in classes

Posted: Sat Nov 08, 2014 6:22 am
by Imran520
I understand it . it is very easy.