Variable scope in PHP class

How to set a global variable in this class? I tried this:

class myClass { $test = "The Test Worked!"; function example() { echo $test; } function example2() { echo $test." again"; } } 

Failed to load the page, fully referencing error 500. Then I tried the following:

 class myClass { public $test = "The Test Worked!"; function example() { echo $test; } function example2() { echo $test." again"; } } 

But when I printed both of these, all I see again is "Sorry for such a simple question!

Thanks!

+8
scope php
source share
5 answers

this variable can be obtained as follows

 echo $this->test; 
+17
source share

If you need an instance variable (stored only for this instance of the class), use:

 $this->test 

(as suggested by another answer).

If you want the variable "class", attach it with the keyword "static" as follows:

A class variable differs from an instance variable in that all instances of objects created from the class will have the same variable.

(Note to access class variables, use the Class Name or "I" followed by "::")

 class myClass { public static $test = "The Test Worked!"; function example() { echo self::$test; } function example2() { echo self::$test." again"; } } 

Finally, if you want a true constant (immutable), use 'const' in front (access it again with 'self' plus '::' plus the name of the constant (although this time skip '$'):

 class myClass { const test = "The Test Worked!"; function example() { echo self::test; } function example2() { echo self::test." again"; } } 
+7
source share
 class Foo { public $bar = 'bar'; function baz() { $bar; // refers to local variable inside function, currently undefined $this->bar; // refers to property $bar of $this object, // ie the value 'bar' } } $foo = new Foo(); $foo->bar; // refers to property $bar of object $foo, ie the value 'bar' 

Please start reading here: http://php.net/manual/en/language.oop5.basic.php

+5
source share

There are two ways to access a variable or function in a class, either inside the class or outside it, if they request the element public (or in some cases protected)

 class myClass { public $test = "The Test Worked!"; function example() { echo $this->test; // or with the scope resolution operator echo myClass::test; } function example2() { echo $this->test." again"; // or with the scope resolution operator echo myClass::test." again"; } } 
+3
source share

Try adding $this to the front of your variables; you can change the second example to

 class myClass { public $test = "The Test Worked!"; function example() { echo $this->test; } function example2(){ echo $this->test." again"; } } 
+1
source share

Source: https://habr.com/ru/post/649886/


All Articles