Setting public class variables Setting public class variables php php

Setting public class variables


this is the way, but i would suggest to write a getter and setter for that variable.

class Testclass{    private $testvar = "default value";    public function setTestvar($testvar) {         $this->testvar = $testvar;     }    public function getTestvar() {         return $this->testvar;     }    function dosomething()    {        echo $this->getTestvar();    }}$Testclass = new Testclass();$Testclass->setTestvar("another value");$Testclass->dosomething();


Use Constructors.

<?phpclass TestClass{    public $testVar = "default value";    public function __construct($varValue)    {       $this->testVar = $varValue;                   }}    $object = new TestClass('another value');print $object->testVar;?>


class Testclass{  public $testvar;  function dosomething()  {    echo $this->testvar;  }}$Testclass = new Testclass();$Testclass->testvar = "another value";    $Testclass->dosomething(); ////It will print "another value"