Where are php variables generally placed?
The required format for defining variables in php is very loose. As for Where you define variables depends on your needs. You can define local variables in the constructor, in the method you define, or you can define global variables outside the constructor.
// 局部变量 函数内部 function demo1() { $str1 = "我是demo1中的变量str1"; return $str1; } // 在函数内部访问 //echo demo1();
// 全局变量 在函数外部 $str2 = "我是demo2中的外部变量str1"; function demo2() { return $str2 ? : '不可访问'; } echo demo2(); echo $str2;
// 构造函数 在类里 class User{ public $user_name; public $age; public function __construct($user_name,$age) { $this->user_name = $user_name; $this->age = $age; } } $obj1 = new User('张三',28); //用户1
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of Where are php variables generally placed?. For more information, please follow other related articles on the PHP Chinese website!