在 php 中实例化私有 class

Instantiate a private class in php

我正在尝试使用私有内部变量访问 Dog class,并且我正在尝试在底部实例化这些变量,尽管它 运行 它不会改变 "loud to " LOUD”的树皮,谁能解释为什么会这样?

__construct 故意留空

class Dog {
    private $_bark='loud'; //how loud the bark is
    private $_goodBoy='yes';//how well dog behaves
    private $_wetnessOfNose='moist';//how wet the dog nose is 

    public function __construct() {
    }

    public function bark() {
        // retrieves how loud the bark is
        return $this->_bark;
    }

    public function goodboy() {
        // retrieves status of dog behavior
        return $this->_goodBoy;
    }

    public function nose() {
        // retrieves how wet dogs nose is
        return $this -> _wetnessOfNose;
    }
}

$myDog= new Dog();
$myDog->bark('LOUD');
echo "myDog's bark is " . $myDog->bark();

您没有更改变量 $_bark 的值,您返回的是一个值。当没有什么可提供时,您正在为函数 bark 提供参数。

class Dog {
    private $_bark='loud';       // how loud the bark is
    private $_goodBoy='yes';     // how well dog behaves
    private $_wetnessOfNose='moist';    // how wet the dog nose is

    public function setBark($newBark){
        //sets how loud the bark is
        $this->_bark = $newBark;
    }

    public function bark(){
        //retrieves how loud the bark is
        return $this->_bark;
    }

    public function goodboy(){
        //retrieves status of dog behavior
        return $this->_goodBoy;
    }

    public function nose(){
        //retrieves how wet dogs nose is
        return $this -> _wetnessOfNose;
    }
}

$myDog= new Dog();
$myDog->setBark('LOUD');
echo "myDog's bark is " . $myDog->bark();

你的bark()好像是getter,不是setter,所以调用

$myDog->bark('LOUD');

完全没有意义,因为它没有使用 return 值 + 你尝试传递参数,即使没有人期望它。

最好将 getter 命名为 getBark() 并将 setter 命名为 setBark() 以避免此类问题,您应该删除当前的 bark()并介绍

public function getBark(){
    return $this->_bark;
}

public function setBark($bark){
    $this->_bark = $bark;
}

您写了 getter,但没有写 setter。要设置私有 属性,您需要编写 class 方法来设置私有 属性。

getters 和 setters

您可以编写两种方法,getBarksetBark(可能是最自我记录的),前者是 return $_bark,后者是采用 $bark 参数并将 $this->_bark 设置为 $bark.

示例:

public function getBark() {
    return $_bark;
}

public function setBark($bark) {
    $this->_bark = $bark;
}

合并 getter 和 setter

或者,您可以结合使用 getset 方法,然后像现在一样使用 bark 方法。它应该使用 $bark 参数并使用 PHP 的 isset() function 检查它是否不是 null,然后将 $_bark 设置为 $bark 并退出没有 returning 任何东西的方法。如果参数 $bark 未设置 ,它只是 return 私有 属性 $_bark 的值。因此,从本质上讲,它涵盖了两种方法的职责。

这个方法可以调用$myDog->bark()得到$_bark的值,调用$myDog->bark('LOUD');设置值$_bark'LOUD'.

示例:

public function bark($bark) {
    if (isset($bark)) { // If you've supplied a $bark parameter...
        $this->_bark = $bark; // Set $_bark to the value of the parameter
        return; // Exit the method without returning anything (does not continue outside of the if statement
    }

    return $this->_bark; // No parameter was supplied, so just return the value of $_bark
}

不好的做法

最后,你可以_bark属性public,但你真的不应该那样做。