Home > Backend Development > PHP Problem > What is the method to define variables in php class

What is the method to define variables in php class

PHPz
Release: 2023-03-31 11:20:01
Original
1802 people have browsed it

In PHP classes, there are two ways to define variables: attributes and constants.

  1. Attributes

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;
    }
}
Copy after login
  1. Constant

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;
    }
}
Copy after login

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!

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