Home > Backend Development > PHP Problem > Where are php variables generally placed?

Where are php variables generally placed?

angryTom
Release: 2023-02-28 08:36:02
Original
1963 people have browsed it

Where are php variables generally placed?

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();
Copy after login
// 全局变量 在函数外部
$str2 = "我是demo2中的外部变量str1";
function demo2()
{
    return $str2 ? : '不可访问';
}
echo demo2();
echo $str2;
Copy after login
// 构造函数 在类里
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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template