In PHP classes, there are two ways to define variables: attributes and constants.
Attributes are variables defined in the class and can be accessed and modified throughout the class. In PHP, there are three access control symbols for properties: public, protected, and private.
Public properties are accessible throughout the script, protected properties are only accessible within the current class and subclasses, and private properties are only accessible within the current class.
The following is an example of defining attributes:
class Person { public $name; // 公共属性 protected $age; // 受保护属性 private $gender; // 私有属性 function __construct($name, $age, $gender) { $this->name = $name; $this->age = $age; $this->gender = $gender; } }
Constant is also a variable defined in the class, but once defined, it cannot be modified. In PHP, constants are defined using the const keyword.
Constants are public by default, so they can be accessed throughout the script. Constant names must be in uppercase letters, and it is recommended to use underscores to separate words when naming to improve readability.
The following is an example of defining a constant:
class Math { const PI = 3.1415926; function circleArea($r) { return self::PI * $r * $r; } }
In the above example, we define a Math class and define a constant named PI in it. We also used the self keyword to access constants.
Summary
In PHP classes, there are two ways to define variables: attributes and constants. Properties can be accessed and modified throughout the class, whereas constants cannot be modified once defined. It's important to learn these basic concepts because they are the basis for understanding how objects and classes work in PHP.
The above is the detailed content of What is the method to define variables in php class. For more information, please follow other related articles on the PHP Chinese website!