How to modify or set a value inside the class in php

2

I have class in php and I need to modify the value of private $key = "valor"; out of class .

How can I change the value of $key outside this class? The value I want to put in $key comes from a $_POST["name"] .

class Webcmd {
    private $key = "valor padrão a ser modificado";
    function __construct(){}
    ...
}

I could not find a way to set this value out of class Webcmd and now I also can not set a value that is being passed via POST .

How can I do this?

    
asked by anonymous 28.06.2015 / 06:08

1 answer

3

To change the state of some attribute of a class it is common to create accessor methods get for reading and set for writing, so you can centralize some simple validations.

If this value does not need to be changed you can change the setter by a parameter in the constructor.

<?php

class Webcmd {
    private $key = "valor padrão a ser modificado";
    function __construct() {
    }

    public function getKey() {
        return $this->key;
    }

    public function setKey($key) {
        $this->key = $key;
    }

}

//chamada
$web = new Webcmd();
$web->setKey('Novo valor');
echo $web->getKey();

Related:

When to use Setters and Getters?

Getters and Setters can only "walk" together?

Getters and setters are an illusion of encapsulation?

    
28.06.2015 / 06:15