Static method
(1) Static methods cannot access ordinary properties in this class, because those properties belong to an object, but they can be accessed Static properties;
(2) To access static methods or properties from the current class (not a subclass), you can use the self keyword, self points to the current class, just like $this points to the current object;
(3) Static methods cannot be called in objects. Static methods and attributes are also called class methods and class attributes, so the pseudo variable $this cannot be used in objects.
Advantages of static methods: (Recommended learning: PHP programming from entry to proficiency)
(1) It can be used anywhere in the code Use (assuming the class can be accessed);
(2) Each instance of the class can access the static properties defined in the class, and can use static properties to set values, which can be used by all objects of the class ;
(3) Static properties or methods can be accessed without an instance object.
<?php $pdo = new PDO('mysql:host=localhost;dbname=mydb','root'); // 生成一个 PDO(PHP Data Object) 对象 class ShopProduct{ private $title; // 属性也称为成员变量,用来存放对象之间互不相同的数据 private $producerMainName; // 所有的属性都设置为 private,不允许外部直接访问这些属性,然后提供方法来取得需要的值 private $producerFirstName; protected $price; // 阻止外面直接访问该属性,可以被子类访问 private $discount = 0; private $id = 0; // 创建对象时,构造方法会被自动调用,构造方法可以确保必要的属性设置,并完成任何需要准备的工作 public function __construct($title,$mainName,$firstName,$price){ $this->title = $title; // 使用伪变量$this给每个变量赋值 $this->producerMainName = $mainName; $this->producerFirstName = $firstName; $this->price = $price; } /** * @return mixed 这种只返回属性值的方法称为“访问方法”,也称为 getter 和 setter */ public function getProducerFirstName() { return $this->producerFirstName; } /** * @return mixed 获取 姓 的访问方法 */ public function getProducerMainName() { return $this->producerMainName; } /** * @param $num 打折的价格 */ public function setDiscount($num) { $this->discount = $num; } /** * @return int 折扣的访问方法 */ public function getDiscount() { return $this->discount; } /** * @return mixed Book名或CD名的访问方法 */ public function getTitle() { return $this->title; } /** * @return mixed 折扣后的价格 */ public function getPrice() { return ($this->price - $this->discount); } /** * @return string 作者 */ public function getProducer(){ // 方法让对象执行任务 return $this->producerMainName .' '. $this->producerFirstName; } /** * @return string 发票的摘要信息 */ public function getSummaryLine() { $base = "{$this->title} ( {$this->producerMainName},{$this->producerFirstName}) "; return $base; } /** * @param $id id 的访问方法, setter */ public function setId($id) { $this->id = $id; } // 根据查询数据的数据类型,返回特定类型的 ShopProduct 对象,这个方法没有使用任何实例的属性和方法,因此把它定义为一个静态方法(static),只要有一个有效的 PDO 对象,就可以在程序的任何地方调用这个方法。这个方法就像工厂一样,可以接受原始数据产生特定类型的对象。 public static function getInstance($id,PDO $pdo) { $stmt = $pdo -> prepare("SELECT * FROM products WHERE id=?"); $stmt -> execute(array($id)); $row = $stmt -> fetch(); if(empty($row)){ return null; } switch($row['type']) { case 'book' : $product = new BookProduct($row['title'],$row['first_name'],$row['main_name'],$row['price'],$row['num_pages']); break; case 'cd' : $product = new CdProduct($row['title'],$row['first_name'],$row['main_name'],$row['price'],$row['play_length']); break; default : $product = new ShopProduct($row['title'],$row['first_name'],$row['main_name'],$row['price']); break; } $product -> setId($row['id']); $product -> setDiscount($row['discount']); return $product; } } // 若派生类没有定义构造方法,则它在实例化是会自动调用父类的构造方法。子类默认继承父类所有的 public 和 protected 方法,但不继承 private 方法和属性 class BookProduct extends ShopProduct { private $numPages; // 每个子类在设置自己的属性前调用父类的构造方法,基类现在仅知道自己的数据,子类一般是父类的特列,应该避免告诉父类任何关于子类的消息。 public function __construct($title,$mainName,$firstName,$price,$numPages) { // parent 关键字可以在任何复写父类方法的方法中使用,通过在当前对象中调用父类的方法来拓展父类的功能 , 要应用一个类而不是对象的方法,使用 :: 而不是 -> parent::__construct($title,$mainName,$firstName,$price); $this -> numPages = $numPages; } /** * @param $numPages 书的页数 * @return mixed 总页数 */ public function getNumberOfPages() { return $this->numPages; } /** * 子类(派生类)可以覆盖和修改父类(基类或超类)的功能 * @return string Book发票的摘要信息 */ public function getSummaryLine() { $base = parent::getSummaryLine(); $base .= "page count - {$this->numPages}"; return $base; } } class CdProduct extends ShopProduct { private $playLength; public function __construct($title,$mainName,$firstName,$price,$playLength) { parent::__construct($title,$mainName,$firstName,$price); $this -> playLength = $playLength; } /** * @return int 播放时间 */ public function getPlayLength() { return $this -> playLength; } /** * @return string CD发票的摘要信息 */ public function getSummaryLine() { $base = parent::getSummaryLine(); $base .= "playing time - {$this->playLength}"; return $base; } } $product = ShopProduct::getInstance(1,$pdo); // 该静态方法根据传入 id 的不同生成特定类型的对象 if($product){ print "author : {$product -> getProducer()} </br>"; // author :Lun Xun print "summary line: {$product -> getSummaryLine()}</br>"; // summary line: Kong Yiji ( Xun,Lun) page count - 200 }
Attached (pictures of sql files and data):
The above is the detailed content of What is the use of php static methods?. For more information, please follow other related articles on the PHP Chinese website!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.