search
HomeBackend DevelopmentPHP Tutorial关于静态方法和属性

目录Table Of Contents

  • 为什么要使用静态方法和属性?

静态方法和属性

静态方法和属性,其实就是通过类而不是通过对象来访问数据和功能。

面向对象编程中的实际操作都是通过类的实例(而不是类本身)完成的,毕竟类只是实例的模板。但是我们可以通过static来访问类的方法和属性,这相当于就是静态的,没有动态的实例化类,而是静态的直接调用。

静态方法是以类为作用域的函数,静态方法不能访问这个类中的普通属性,因为这些属性是属于一个对象的,但可以访问静态属性。

因为通过类而不是实例来访问静态元素,所以访问静态元素时不需要引用对象的变量,而是使用双冒号 ::来访问。

StaticExample::sayHello();

一个子类可以用parent关键字来访问父类,而不使用其类名。要从类(不是子类)中访问静态方法和属性,可以使用self关键字,self指向当前类,就像$this指向当前对象一样。

为什么要使用静态方法和属性?

1.因为他们在代码中任务地方都可用,也就是说,你不需要再对象间传递类的实例,也不需要讲实例存放在全局变量中,就可以访问类的方法和属性。

2.类的每个实例都可以访问类中定义的静态属性,所以你可以利用静态属性来设置值,该值可以被雷的所有对象使用。

3.不需要实例对象就能访问静态属性和方法,这样我们就可以不用为了获取一个简单的功能而实例化对象。

< ?phpclass ShopProduct{    private $id = 0;    public function setID($id){        $this->id = $id;    }    public static function getInstance($id, PDO $pdo){  //关键在这里,getinstance方法是一个静态方法,并且传入的是2个参数,一个是id一个是pdo的实例        $stmt = $pdo->prepare("select * from products where id=?");        $result = $stmt->execute(arrary($id));        $product = new BookProduct($result['title']);  //这里特地设置了一个特定类型的shopproduct对象,这是一个book的shopproduct对象        $product->setID($result['id']);        return $product; //这个方法没有使用任何实例的属性和方法,只要有一个有效的pdo对象,我们就可以在程序任何地方调用它,并且他返回的是一个特定类型的Shopproduct对象    }}$dsn = "sqlite://XXXXXX/products.db";$pdo = new PDO($dsn,null,null);$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMOTE_EXCEPTION);$obj = ShopProduct::getInstance(1, $pdo); //在这里,我们就直接调用了,而没有实例化对象。并且,pdo对象也是可以随时更换的,不用约束在某个pdo对象上。?>

这样的方法就像工厂一样,可以接受原始数据,然后根据这些数据产生对象。

Statement
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools