K
K
Karponter2014-07-24 20:57:29
linux
Karponter, 2014-07-24 20:57:29

How to properly use methods and attributes of PHP classes?

I started to study OOP in terms of PHP and stumbled on the very first steps. What am I actually wrong in this example?

<?php
  class ClassName
  {
    var $myTestVar = 0;

    function readVar() {
      echo $this->$myTestVar;
    }
  }

  $a = new ClassName();
  $a->readVar();
?>

Validator says:
PHP Notice: Undefined variable: myTestVar in ~/.../test.php on line 13
PHP Fatal error: Cannot access empty property in ~/.../test.php on line 13

Problem in the code or with the validator?
update...
<?php
  class ClassName
  {
    public $myTestVar;

    public function __construct() 
    {
      $this->myTestVar  = 0;
    }

    function readVar() {
      echo $this->$myTestVar;
    }
  }

  $a = new ClassName();
  $a->readVar();
?>

Exodus is the same.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vdem, 2014-07-24
@karponter

Extra $, instead of:
need
echo $this->myTestVar;

P
Push Pull, 2014-07-24
@deadbyelpy

We started to study the OOP model, do not write class fields in the old style,
write as it should
, or make a static field if necessary.
this one var $myTestVar = 0;already makes it static, so $this->myTestVar is empty
If you want to specify default values, write in the constructor

public function __construct() 
{
    $this->myTestVar  = 0;
}

S
Sergey, 2014-07-24
Protko @Fesor

Take the trouble to read the documentation first. And it is the documentation and not the articles of Vasya Pupkin. There it is even translated into Russian (what about OOP), and the basics are very well disclosed there. I also advise you to connect Wikipedia and read about "encapsulation".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question