Answer the question
In order to leave comments, you need to log in
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();
?>
PHP Notice: Undefined variable: myTestVar in ~/.../test.php on line 13
PHP Fatal error: Cannot access empty property in ~/.../test.php on line 13
<?php
class ClassName
{
public $myTestVar;
public function __construct()
{
$this->myTestVar = 0;
}
function readVar() {
echo $this->$myTestVar;
}
}
$a = new ClassName();
$a->readVar();
?>
Answer the question
In order to leave comments, you need to log in
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;
}
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 questionAsk a Question
731 491 924 answers to any question