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
https://forums.phpfreaks.com/topic/210696-why-it-uses-the-constructor/
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.

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.