Home Backend Development PHP Tutorial PHP Object-Oriented Journey: Deep Understanding of Static Variables and Methods_PHP Tutorial

PHP Object-Oriented Journey: Deep Understanding of Static Variables and Methods_PHP Tutorial

Jul 13, 2016 am 10:41 AM
php static and Keywords variable statement object Attributes method yes go deep understand For

The static keyword declares that an attribute or method is related to the class, rather than to a specific instance of the class. Therefore, this type of attribute or method is also called "class attribute" or "class method".

If access control permissions allow, you can call it directly using the class name plus two colons "::" without creating an object of this class.

The static keyword can be used to modify variables and methods.

You can directly access the static properties and static methods in the class without instantiation.

Static properties and methods can only access static properties and methods, and non-static properties and methods cannot be accessed by class. Because when static properties and methods are created, there may not yet be any instances of this class that can be called.

Static attributes have only one copy in memory and are shared by all instances.

Use the self:: keyword to access static members of the current class.
Public properties of static properties

All instances of a class share static properties in the class.

In other words, even if there are multiple instances in the memory, there is only one copy of the static attributes.

In the following example, a counter $count attribute is set, with private and static modifications. In this way, the outside world cannot directly access the $count property. As a result of the program running, we also see that multiple instances are using the same static $count attribute.

Copy code The code is as follows:

class user{
private static $count = 0 ; //Record the login status of all users.
public function __construct(){
self::$count = self::$count + 1;
}
public function getCount(){
         return self::$count; $user1 = new user();
$user2 = new user();
$user3 = new user();
echo "now here have ".$user1->getCount()." user";
echo "
";
unset( $user3);
echo "now here have ".$user1->getCount()." user";
? >



Program running result:
1
2
now here have 3 usernow here have 2 user jb51.net

Static attribute calls directly

Static properties can be used directly without instantiation, and can be used directly before the class is created.

The method used is class name::static property name.

Copy code

The code is as follows:

class Math{ public static $pi = 3.14 ;
}
//Find the area of ​​a garden with a radius of 3.
$r = 3;
echo "The area of ​​radius $r is
";
echo Math::$pi * $r * $r ;

echo "

";
//I think 3.14 is not accurate enough here, so I set it to be more accurate.
Math::$pi = 3.141592653589793;
echo "The area of ​​radius $r is
";
echo Math::$pi * $r * $r ;
?> ;



Program running results:
1
2
3
4

The area with a radius of 3 is
28.26
The area with a radius of 3 is
28.2743338823

The class is not created, and the static attributes can be used directly. When are static properties created in memory? I haven't seen any relevant information in PHP. Citing concepts in Java to explain should also be universal.

Static properties and methods, created when the class is called. When a class is called, it means that the class is created or any static member in the class is called.
Static method

Static methods can be used directly without the class being instantiated.

The method used is class name:: static method name.


Let’s continue writing this Math class to perform mathematical calculations. We design a method to calculate the maximum value. Since it is a mathematical operation, we do not need to instantiate this class. It would be much more convenient if this method can be taken and used.

We designed this class just to demonstrate the static method. PHP provides the max() function to compare numerical values.

Copy code

The code is as follows:


class Math{

public static function Max($num1,$num2){
return $num1 > $num2 ? $num1 : $num2;
}  
}
$a = 99;
$b = 88;
echo "Show that the maximum value between $ a and $ b is";
echo "echo Math::Max($a,$b);
echo "
";echo "
";echo "
";
$ a = 99;
$b = 100;
echo "Show the maximum value between $ a and $ b is";
echo "
";
echo Math::Max( $a,$b);
?>

Program running results:

Displays that the maximum value in $a and $b is
99
Displays that the maximum value in $a and $b is
100
Static How to call static method

The first example, when a static method calls other static methods, use the class name directly.

Copy code The code is as follows:

// Math class that implements maximum value comparison.
class Math{

public static function Max($num1,$num2){
return $num1 > $num2 ? $num1 : $num2;
}
public static function Max3($num1,$num2,$num3){
           $num1 = Math::Max($num1,$num2);
            $num2 = Math::Max($num2,$num3);
$num1 = Math::Max($num1,$num2);
return $num1;
}
}
$a = 99;
$b = 77;
$c = 88;
echo "Show the maximum value in $a $b $c is";
echo "
";
echo Math::Max3($a,$b ,$c);
?>

Program running result:
1
2

Displays that the maximum value among 99 77 88 is
99

You can also use self:: to call other static methods in the current class. (Suggestion)

Copy code The code is as follows:

// Math class that implements maximum value comparison.
class Math{

public static function Max($num1,$num2){
return $num1 > $num2 ? $num1 : $num2;
}
public static function Max3($num1,$num2,$num3){
$num1 = self::Max($num1,$num2);
$num2 = self::Max($num2,$num3);
$num1 = self::Max($num1,$num2);
return $num1;
}
}
$a = 99;
$b = 77;
$c = 88;
echo "Show the maximum value in $a $b $c is";
echo "
";
echo Math::Max3($a,$b ,$c);
?>

Program running result:
1
2

Displays that the maximum value among 99 77 88 is
99
Static method calls static property

Use class name::static property name to call the static properties in this class.

Copy code The code is as follows:

//
class Circle{
public static $pi = 3.14;

public static function circleAcreage($r){
return $r * $r * Circle::$pi;
}
}
$r = 3;
echo "The area of ​​a circle with radius $r is" . Circle::circleAcreage($r);
?>

Program execution result:
1

The area of ​​a circle with radius 3 is 28.26

Use self:: to call the static properties of this class. (Suggestion)

Copy code The code is as follows:

//
class Circle{
public static $pi = 3.14;

public static function circleAcreage($r){
return $r * $r * self::$pi;
}
}
$r = 3;
echo "The area of ​​a circle with radius $r is" . Circle::circleAcreage($r);
?>

Program running results:
1

The area of ​​a circle with radius 3 is 28.26
Static methods cannot call non-static properties

Static methods cannot call non-static properties. Non-static properties cannot be called using self::.

Copy code The code is as follows:

//
class Circle{
public $pi = 3.14;

public static function circleAcreage($r){
return $r * $r * self::pi;
}
}
$r = 3;
echo "The area of ​​a circle with radius $r is" . Circle::circleAcreage($r);
?>

Program running result:
1

Fatal error: Undefined class constant 'pi' in E:PHPProjectstest.php on line 7

You also cannot use $this to get the value of a non-static property.

Copy code The code is as follows:

//
class Circle{
public $pi = 3.14;

public static function circleAcreage($r){
return $r * $r * $this->pi;
}
}
$r = 3;
echo "The area of ​​a circle with radius $r is" . Circle::circleAcreage($r);
?>

Program running result:
1

Fatal error: Using $this when not in object context in E:PHPProjectstest.php on line 7
Static method calls non-static method

In PHP5, the $this identifier cannot be used in static methods to call non-static methods.

Copy code The code is as follows:

// Math class that implements maximum value comparison.
class Math{
public function Max($num1,$num2){
echo "bad
";
return $num1 > $num2 ? $num1 : $num2;
}
public static function Max3($num1,$num2,$num3){
$num1 = $this->Max($num1,$num2);
$num2 = $this-> ;Max($num2,$num3);
$num1 = $this->Max($num1,$num2);
return $num1;
}
}
$a = 99;
$b = 77;
$c = 188;
echo "Show $a $b $c The maximum value is";
echo "
";
echo Math::Max3($a,$b,$c);
?>

Program running result:

Displays that the maximum value among 99 77 188 is
Fatal error: Using $this when not in object context in E:test.php on line 10

When a non-static method in a class is called by self::, the system will automatically convert this method into a static method.

The following code was executed and produced results. Because the Max method is converted into a static method by the system.

Copy code The code is as follows:

// Math class that implements maximum value comparison.
class Math{
public function Max($num1,$num2){ return $num1 > $num2 ? $num1 : $num2;
}
public static function Max3($ num1,$num2,$num3){
$num1 = self::Max($num1,$num2);
$num2 = self::Max($num2,$num3);
$num1 = self::Max($num1,$num2); 188;
echo "Show the maximum value in $a $b $c is";
echo "
";
echo Math::Max3($a,$b,$c) ;
?>



Program running result:
1
2

Displays that the maximum value among 99 77 188 is
188

In the following example, we let the static method Max3 use self:: to call the non-static method Max, and let the non-static method Max call the non-static property $pi through $this.

An error was reported when running. This error is the same as the previous example 3-1-9.php. This time, the non-static method Max reported an error of calling non-static properties by a static method.

This proves something. The non-static method Max we defined here is automatically converted into a static method by the system.

Copy code

The code is as follows:


// Math class that implements maximum value comparison.
class Math{
public $pi = 3.14;

public function Max($num1,$num2){
echo self::$pi; //The call here does not seem to work There should be a problem.
Return $num1 > $num2 ? $num1 : $num2;
}
public static function Max3($num1,$num2,$num3){
$num1 = self ::Max($num1,$num2);
$num2 = self::Max($num2,$num3);
$num1 = self::Max($num1,$num2);
return $num1;
}
}
$a = 99;
$b = 77;
$c = 188;
echo "Show $a $b $c The maximum value is ";
echo "
";
echo Math::Max3($a,$b,$c);
?>

The program running result:
1
2

The maximum value shown in 99 77 188 is
Fatal error: Access to undeclared static property: Math::$pi in E: PHPProjectstest.php on line 7

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/676925.htmlTechArticleThe static keyword declares that a property or method is related to the class, not to a specific instance of the class Related, therefore, such properties or methods are also called "class properties" or "class methods"...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles