Home  >  Article  >  Backend Development  >  PHP wants to realize that a field cannot be modified after it is assigned a value. How to achieve this?

PHP wants to realize that a field cannot be modified after it is assigned a value. How to achieve this?

WBOY
WBOYOriginal
2016-09-26 08:40:171198browse

php itself does not have modifiers like C# readonly, it should be implemented through design

Reply content:

php itself does not have modifiers like C# readonly, it should be implemented through design

Isn’t it enough to just use constants?
define(key,value)

Talk is cheap,i will show you the code demo.
Like this:

<code>//1.first snippet
class HelloSomeOne{
 const NAME = "PHP技术大全";
 //todo something else.
}
//2. second snippet
//not in class body inner
const NAME = "PHP技术大全";</code>

php does not provide such a function, but in object-oriented design, it can be achieved through the set/get method.

<code>class {
    private $a = null;
    
    public function setA($a) {
        if (null === $this->a) {
            $this->a = $a;
        }
    }

    public function getA() {
        return $this->a;
    }
}</code>

For the set/get method, you can use the two magic functions __set/__get to achieve better writing effect.

You can use define in PHP scripts, and you can use const in PHP classes

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn