Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The best practices of oop is NEVER have public properties in your class. The best way to manipulate properties of your class is to have separate methods that will return the value of the properties and set the value of the properties. So</p> <pre><code>class MyClass { private $say; // common setter, invoked when we trying to set properties as they are public public function __set($name, $value) { $methodname = 'set' . ucfirst(strtolower($name)); if (method_exists($this, $methodname)) { $this-&gt;$methodname($value); } else { throw new Exception ('There is no "' . $name . '" property in "' . __CLASS__ . '" class'); } } // common getter, invoked when we trying to get properties as they are public public function __get($name) { $methodname = 'get' . ucfirst(strtolower($name)); if (method_exists($this, $methodname)) { return $this-&gt;$methodname(); } else { throw new Exception ('There is no "' . $name . '" property in "' . __CLASS__ . '" class'); } } // setter for out private property $say, invoked by common setter when colling $a-&gt;say = "something"; public function setSay($value) { $this-&gt;say = $value; } // getter for out private property $say, invoked by common getter when colling $a-&gt;say; public function getSay() { return $this-&gt;say; } public function Talk($monologue) { $this-&gt;say = (!empty($monologue))?$this-&gt;say:$monologue; return $this-&gt;say; } } </code></pre> <p>So now you can access your private properties as they are public, and do all neccessary checks to not get bad values be stored in them. Like that:</p> <pre><code>$a = new MyClass; $a-&gt;say = "Hello my friends !"; $a-&gt;Talk(); $a-&gt;Talk("Good bye !"); echo $a-&gt;say; </code></pre> <p>Or like that:</p> <pre><code>$a = new MyClass; $a-&gt;setSay("Hello my friends !"); $a-&gt;Talk(); $a-&gt;Talk("Good bye !"); echo $a-&gt;getSay(); </code></pre> <p>For more security, you can make setSay and getSay methods private, but then the second piece of code won't work.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload