setter方法和构造方法有什么区别?

时间:2014-04-15 16:42:35

标签: php oop methods constructor setter

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

我可以随时互换地使用这两者,还是会有一个人最喜欢另一个?

4 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

一般情况下,如果您的类不存在,或者没有值,则使用构造函数来设置值。如果允许更改该值,则添加setter。如果在施工后永远不应该更改,那么不要添加setter。

答案 2 :(得分:1)

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

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