beginning oop php question: do constructors take the place of getter?
- by Joel
I'm working through this tutorial:
http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-3.php
At first he has you create a setter and getter method in the class:
<?php
class person{
var $name;
function set_name($new_name){
$this->name=$new_name;
}
function get_name(){
return $this->name;
}
}
php?>
And then you create the object and echo the results:
<?php
$stefan = new person();
$jimmy = new person();
$stefan ->set_name("Stefan Mischook");
$jimmy ->set_name("Nick Waddles");
echo "The first Object name is: ".$stefan->get_name();
echo "The second Object name is: ".$jimmy->get_name();
?>
Works as expected, and I understand.
Then he introduces constructors:
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;
}
}
And returns like so:
<?php
$joel = new person("Joel");
echo "The third Object name is: ".$joel->get_name();
?>
This is all fine and makes sense.
Then I tried to combine the two and got an error, so I'm curious-is a constructor always taking the place of a "get" function? If you have a constructor, do you always need to include an argument when creating an object?
Gives errors:
<?php
$stefan = new person();
$jimmy = new person();
$joel = new person("Joel Laviolette");
$stefan ->set_name("Stefan Mischook");
$jimmy ->set_name("Nick Waddles");
echo "The first Object name is: ".$stefan->get_name();
echo "The second Object name is: ".$jimmy->get_name();
echo "The third Object name is: ".$joel->get_name();
?>