setter方法和construct方法之间的区别是什么


What is the difference between setter methods and construct methods?

如果我有下面的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();
?>

我可以随时交替使用这两种吗?或者在某些情况下,一种会比另一种更受欢迎吗?

关于您的问题,还有一些很好的解释:http://www.potstuck.com/2009/01/08/php-dependency-injection/

试试这个网站。它用例子说明了一切。http://ralphschindler.com/2012/03/09/php-constructor-best-practices-and-the-prototype-pattern

通常,如果没有值,类就不存在或没有意义,则使用构造函数来设置值。如果允许更改值,则添加一个setter。如果在构建后永远不应该更改它,那么就不要添加setter。

示例代码:

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