Jump to content

why it uses the Constructor?


runeveryday

Recommended Posts

class 1:

 class HelloWorld { public $world; function getHtml() { return "<html><body>". "Hello, ".$this->world."!". "</body></html>"; } }

 

class2:

class HelloWorld {
public $world;
function __construct($world) {
$this->world = $world;
}
function getHtml() {
return "<html><body>".
"Hello ".$this->world."!".
"</body></html>";
}
}

 

i don't know why in class 2 it uses a construct function. i feel it is unnecessary .any tips would be appreciated.

 

Link to comment
Share on other sites

The proper method would be:

 

class SomeOddWorld {
    private $theOddWorldsName;
    
    public function __construct($nameIt) {
        $this->theOddWorldsName = $nameIt;
    }
}

 

Ditch the getHtml() method it's against proper design. Every model should be free of storing and presenting itself.

Link to comment
Share on other sites

The proper method would be:

 

class SomeOddWorld {
    private $theOddWorldsName;
    
    public function __construct($nameIt) {
        $this->theOddWorldsName = $nameIt;
    }
}

 

Ditch the getHtml() method it's against proper design. Every model should be free of storing and presenting itself.

i am still confused.

Link to comment
Share on other sites

i am still confused.

 

OOP is about encapsulating your data, which means that the data is hidden from the client. If you declare your class variables public you are no longer encapsulating this data. It's best to always declare your class variables private NOT public and only in VERY rare cases should you use protected.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.