Timothy Coetzee Timothy Coetzee - 4 years ago 179
PHP Question

PHP OOP Construct explination unclear

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();


Fine I get that no problem However it then goes on giving, what is in my view a very brief explanation on constructors, saying:

Wouldn't it be nice if you could both create and initialize an object at the same time, PHP allows you to do that with constructors.

And then proceeds to give the following example
EXAMPLE 2(UNCLEAR...?)

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(), ".";


My Question

I would really like to know what is the difference between the two examples above? Also if a beginner practical example could be included it will be enormously appreciated!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download