can you explain this to me

Associate
Joined
19 Jul 2006
Posts
1,847
OK so I have this
PHP:
<?php
	class person{
		var $name;
        
        function __construct($persons_name)
        {
            $this->name =$persons_name;
        }
		function set_name($new_name){
			$this->name = $new_name;
		}
		function get_name(){
			return $this->name;
		}
	}

if I do this
PHP:
$dave = new person();
    $matthew = new person('Matthew Smith');

I get warnings and notices about the missing argument and undeclared variable for $dave as I expected. I understand all of that.
To fix it I have seen
PHP:
 function __construct($persons_name = NULL)
        {
            $this->name =$persons_name;
        }

Which works and gets rid of the errors. can you explain to me why though.

Why does $sam = new person('sam'); get the name set to sam? I know we are sending it into the constructor as $persons_name but we are also setting $persons_name to NULL in the constructor.

The code works I just want to understand the function __construct($persons_name = NULL) bit
 
Yeah that's what's happening
its just in my head when you assign a variable eg
$x = 'name' then from there on in $x == name until you reassign it.

so my thinking ( which is wrong )
PHP:
 function __construct($persons_name = NULL)

we have set $persons_name to be null then any reference to it after that should be null.
 
Back
Top Bottom