How to have a variable accessing through different class methods in PHP?
How is it possible to have a variable inside a class in PHP开发者_如何学Go that is accessible through different methods of the same class? What's the location and syntax of declaration, initialization and accessing?
Here's a simple example.
<?php
class HelloWorld {
var $message = '';
function __construct() {
$this->message = 'Hello World';
}
function say_hi() {
echo $this->message;
}
}
?>
Please read "Classes and Objects: The Basics" in the PHP manual:
http://php.net/manual/en/language.oop5.php
You can access every variable from your class in all the methods with this :
$this->myVar;
a variable can be declared inside the class.
<?php
class ExampleClass {
public $pub; // accessable anywhere
protected $pro; // can only be called by this class and classes that extend this class (inherit)
private $pri; // only accessed by this class
}?>
Variable scope is explained here
精彩评论