This is not a question about a particular problem, but rather a question asking for advice and / or assistance.
Im a 2nd year student, Im really struggling to get the hang of OOP programming, the fact that my textbook is not very clear, in its explanation is not helping either. I know there are 100's of examples on the web of this probably but I would like to focus specifically on the example used in my textbook.
The introduction to OOP in php starts with this:
EXAMPLE 1
class Person{
var $name;
function set_name($data){
$this->name=$data;
}
function get_name(){
return $this->name;
}
}
$ralph = new Person;
$ralph->set_name('Ralph');
echo 'friend name is '.$ralph->get_name();
class Person{
var $name;
function __construct($data)
{
$this->name=$data
}
function set_name($data){
$this->name=$data;
}
function get_name(){
return $this->name;
}
}
$dan = new Person;
echo"Friend name is ", $dan->get_name(), ".";
It's no wonder you are confused, that is a very bad example (looks like they forgot to include passing the name to the constructor)! There are also some outdated styles here as well, typically people do not use var
anymore for property declarations but declare their scope (public
, private
, protected
, etc.), also some syntax errors (missing semicolon), but that is for another day.
What would have made this a lot more clear is if they actually used the new power of the constructor, which for some reason, they did not. Here is an updated example where the constructor is actually being used:
class Person{
private $name;
function __construct($data)
{
$this->name=$data;
}
function set_name($data){
$this->name=$data;
}
function get_name(){
return $this->name;
}
}
// pass the name to the constructor and you can bypass the set_name call
$dan = new Person("Timothy");
echo "Friend name is ", $dan->get_name(), ".";
This definitely gets much more useful than passing scalars, but hopefully it illustrates what constructors can do a little bit better. Constructors are called automatically whenever you instantiate a new object from a class. Let me know if you have any questions.