Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting public class variables

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();
like image 466
Cudos Avatar asked Dec 30 '09 17:12

Cudos


People also ask

Can class variables be public?

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.

Why is it not recommended to make all of classes variable public?

Public variables in general in a class are a bad idea. Since this means other classes/programs, can modify the state of instances.

How do you declare a class variable?

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.


3 Answers

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();
like image 78
ahmetunal Avatar answered Oct 13 '22 09:10

ahmetunal


Use Constructors.

<?php
class TestClass
{
    public $testVar = "default value";
    public function __construct($varValue)
    {
       $this->testVar = $varValue;               
    }
}    
$object = new TestClass('another value');
print $object->testVar;
?>
like image 41
Srikar Doddi Avatar answered Oct 13 '22 09:10

Srikar Doddi


class Testclass
{
  public $testvar;

  function dosomething()
  {
    echo $this->testvar;
  }
}

$Testclass = new Testclass();
$Testclass->testvar = "another value";    
$Testclass->dosomething(); ////It will print "another value"
like image 43
Gurunatha Dogi Avatar answered Oct 13 '22 08:10

Gurunatha Dogi