Search code examples
phpclassprivateinstantiation

Instantiate a private class in php


I am trying to access the Dog class with private internal variables and I am trying to instantiate these variables at the bottom, though it does run it does not change "loud to "LOUD" for bark, can anyone explain why this happening?

__construct is purposely left blank

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

Solution

  • You've written getters, but not setters. To set a private property, you will need to write class methods that set that private property.

    Getters and setters

    You could write two methods, getBark and setBark (likely the most self-documenting), the former of which would return $_bark and the latter would take a $bark parameter and set $this->_bark to $bark.

    Example:

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

    Combined getter and setter

    Alternatively, you could combine both the get and set methods and just use a bark method like you currently have. It should take a $bark parameter and check if it's not null using PHP's isset() function, then set $_bark to $bark and exit the method without returning anything. If the parameter $bark is not set, it just returns the value of the private property $_bark. So, essentially, it covers the duty of both methods.

    This method can be called as $myDog->bark() to get the value of $_bark, or called as $myDog->bark('LOUD'); to set the value of $_bark to 'LOUD'.

    Example:

    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
    }
    

    Bad practice

    Finally, you could make the _bark property public, but you really shouldn't do that.