How do I set a public variable. Is this correct?:
class Testclass
{
public $testvar = "default value";
function dosomething()
{
echo $this->testvar;
}
}
$Testclass = new Testclass();
$Testclass->testvar = "another value";
$Testclass->dosomething();
Public variables, are variables that are visible to all classes. Private variables, are variables that are visible only to the class to which they belong. Protected variables, are variables that are visible only to the class to which they belong, and any subclasses.
Public variables in general in a class are a bad idea. Since this means other classes/programs, can modify the state of instances.
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
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.
<?php
class 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With