runeveryday Posted August 14, 2010 Share Posted August 14, 2010 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 More sharing options...
ignace Posted August 14, 2010 Share Posted August 14, 2010 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 https://forums.phpfreaks.com/topic/210696-why-it-uses-the-constructor/#findComment-1099120 Share on other sites More sharing options...
runeveryday Posted August 14, 2010 Author Share Posted August 14, 2010 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 https://forums.phpfreaks.com/topic/210696-why-it-uses-the-constructor/#findComment-1099126 Share on other sites More sharing options...
ignace Posted August 14, 2010 Share Posted August 14, 2010 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 https://forums.phpfreaks.com/topic/210696-why-it-uses-the-constructor/#findComment-1099251 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.