beginning oop php question: do constructors take the place of getter?

JesseV

New Member
I'm working through this tutorial:http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-3.phpAt first he has you create a setter and getter method in the class:\[code\]<?phpclass person{ var $name; function set_name($new_name){ $this->name=$new_name; } function get_name(){ return $this->name; }}php?>\[/code\]And then you create the object and echo the results:\[code\]<?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();?>\[/code\]Works as expected, and I understand.Then he introduces constructors:\[code\]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; }}\[/code\]And returns like so:\[code\]<?php $joel = new person("Joel"); echo "The third Object name is: ".$joel->get_name();?>\[/code\]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:\[code\]<?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();?>\[/code\]
 
Back
Top