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

Asked

Viewed 1,754 times

2

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

How can I change the value of $key out of 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 couldn’t find a way to define that value outside the class Webcmd and now I can’t either set a value that is being passed via POST.

How can I do that?

  • Tried to create a Setter?

  • No, I don’t usually wear class. I tried some "things" I found researching, but none worked.

1 answer

3


To change the state of an attribute of a class it is common to create access methods get for reading and set for writing, in this way it is possible to centralize some simple validations.

If this value does not need to be changed you can exchange the Setter for 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?

  • It worked, I didn’t know you could do it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.