如果我有以下的setter和getter方法:
<?php
class Name{
protected $first ;
public function setNameType($value) {
$this->first = $value;
}
public function getNameType() {
return $this->first;
}
}
$name = new Name;
$name->setNameType("My Name");
echo $name->getNameType();
?>
和像这样的构造方法
<?php
class Name{
protected $first ;
public function __construct($value) {
$this->first = $value;
}
public function getNameType() {
return $this->first;
}
}
$name = new Name("My Name");
echo $name->getNameType();
?>
我可以随时互换地使用这两者,还是会有一个人最喜欢另一个?
答案 0 :(得分:1)
试试这个网站。它通过示例解释了所有内容 http://ralphschindler.com/2012/03/09/php-constructor-best-practices-and-the-prototype-pattern
答案 1 :(得分:1)
一般情况下,如果您的类不存在,或者没有值,则使用构造函数来设置值。如果允许更改该值,则添加setter。如果在施工后永远不应该更改,那么不要添加setter。
答案 2 :(得分:1)
答案 3 :(得分:0)
示例代码:
class Book {
public function __construct() {
$registry = RegistrySingleton::getInstance();
$this->_database = $registry->database;
// or
global $databaseConnection;
$this->_database = $database;
}
}
class Book {
private $_databaseConnection;
public function __construct() { }
public function setDatabaseConnection($databaseConnection) {
$this->_databaseConnection = $databaseConnection;
}
}
$book = new Book();
$book->setDatabase($databaseConnection);
$book = new Book($databaseConnection, $configFile);
$book = new Book();
$book->setDatabase($databaseConnection);
$book->setConfigFile($configFile);
class Container {
public static $_database;
public static function makeBook() {
$book = new Book();
$book->setDatabase(self::$_database);
// more injection...
return $book;
}
}
然后:
$book = Container::makeBook();