This article brings you relevant knowledge about PHP, which mainly introduces object-oriented related issues. The essence of object-oriented programming is to increase the operating subjects of data and functions, that is, objects. I hope everyone has to help.
Recommended study: "PHP Tutorial"
Practical learning of php, thinkphp, Redis, vue, uni-app and other technologies, Recommended open source e-commerce system likeshop, you can learn from ideas, you can go to copyright for free commercial use, gitee download address:
Click to enter the project address
Object-oriented: OOP (objected oriented programming) programming
Process-oriented is a programming idea
The essence of object-oriented programming is to increase the operating subject of data and functions, that is, objects
All data and functions in object-oriented are mostly composed of subjects (objects ) to call and operate
Object-oriented basics
The difference between process-oriented and object-oriented
Object-oriented keywords
- Class: class, defines the outermost structure of the object-oriented subject, used to wrap the subject's data and functions (functions)
- Object: object, a specific representative of a certain type of transaction, also called an instance
- Instantiation: new, the process of generating objects from a class
- Class member: member
- Method: method, which is essentially a function created in the class structure, called Member method or member function
- Attribute: property, essentially a variable created in the class structure, called a member variable
- Class constant: const, essentially created in the class structure Constants
Create objects
<?phpclass People{}$man=new People();# 实例化类,man就是对象var_dump($man);?> # 输出object(People)#1 (0) { } #1表示:对象编号,与类无关,是整个脚本中对象的序号(0)表示:成员变量(属性)个数{}表示:具体成员变量信息(键值对)
Class objects
<?phpclass Buyer{ # 常量声明 const BIG_NAME='BUYER'; # 常量不需要加 $ # 属性声明 # $name; # 错误的,类内部属性必须使用访问修饰限定符 public $name; public $money=0; # 方法声明 function display(){ echo __CLASS__; # 魔术常量,输出类名 # 方法内部变量属于局部变量 }}# 实例化$a = new Buyer();# 属性操作,增删改查echo $a->money;$a->money='20';$a->sex='male';unset($a->name);echo '<br>';# 方法操作$a->display();echo '<br>';var_dump($a);?> # 输出0Buyerobject(Buyer)#1 (2) { ["money"]=> string(2) "20" ["sex"]=> string(4) "male" }
Note: Class constants are not accessed by objects
Access modification qualifier
Modification keyword before a property or method, used to control the access location of the property or method
- public: public, both inside and outside the class Access
- protected: protected, only allowed to be accessed within the relevant class
- private: private, only allowed to be accessed within the defining class
Attributes must have access modifications Qualifier, the method can have no access modification qualifier, the default is public
internal object of the class
$this, an object built into the method, will automatically point to the object of the method being called
$this exists inside the method (for internal use only), so it is equivalent to being inside the structure of the class
- You can access any member modified by the access modification qualifier
- Private members are accessed through public methods (public methods can be accessed outside the class)
<?phpclass Article{ protected $name = 'a'; private $type = 'art'; public function get_name() { var_dump($this); }}$a = new Article();var_dump($a);?> # 输出object(Article)#1 (2) { ["name:protected"]=> string(1) "a" ["type:private"]=> string(3) "art" }
$this represents the object, and the environment where $this is located is inside the method inside the class, so $ The this object is accessed within the class, so all properties and methods are not restricted by access modification qualifiers
- __construct() is a system-built-in magic method. The characteristic of this method is that the object automatically calls it immediately after the object is instantiated
- The purpose of the constructor is to initialize resources, including object properties and other resources
- Once the constructor is defined and the constructor comes with its own parameters, then You can only use the new class name (parameter list) method to instantiate it correctly
- The magic method can also be called by direct calling from the object, but it is of no practical use
<?phpclass Article{ public $name='xiaoli'; private $sex="male"; public function __construct($name,$sex) { $this->name = $name; $this->sex = $sex; }}$a = new Article('xiaowang', 'famale');var_dump($a);?>Destructor method
- __destruct(), automatically called when the object is destroyed, releases resources
- Object destruction
- Object has no variables Pointing (variable points to other data)
- The object is actively destroyed (unset destroys the object variable)
- Script execution ends (automatically releases resources)
PHP When the script is executed, all resources will be released, so the destructor method is generally less used
<?phpclass Article{ protected $name = 'xiaoli'; private $sex = 'famale'; public function __destruct() { // TODO: Implement __destruct() method. echo __FUNCTION__; }}$a=new Article();# 销毁对象$a=1;unset($a);# __destructendecho 'end';?> # 不销毁对象,php在运行结束也会释放资源# end__destructObject passing valueDefinition: Assign the variable holding the object to another variable
In PHP, the value of an object is passed by reference: that is, one object variable is assigned to another variable, and the two variables point to the same object address, that is, there is only one object.
<?phpclass Article{ public $name = 'xiaoli'; public $sex = 'famale';}$a=new Article();$b=$a;var_dump($a,$b);echo '<br>';$a->name="wangxiaohu";var_dump($a,$b);echo '<br>';?> # 输出object(Article)#1 (2) { ["name"]=> string(6) "xiaoli" ["sex"]=> string(6) "famale" } object(Article) #1 (2) { ["name"]=> string(6) "xiaoli" ["sex"]=> string(6) "famale" }object(Article) #1 (2) { ["name"]=> string(10) "wangxiaohu" ["sex"]=> string(6) "famale" } object(Article) #1 (2) { ["name"]=> string(10) "wangxiaohu" ["sex"]=> string(6) "famale" }Range resolution operator ( Class constant access) There are two colons forming "::", which is specially used for
classes to implement class member operations, and the class can directly access class members
- The scope resolution operator is used to access class members for a class (class name)
类名::类成员
- The range resolution operator can also be used by objects as classes ( Not recommended)
$对象名::类成员
- Class constants can only be accessed by classes
<?phpclass Article{ const NAME='ocean';}echo Article::NAME; # 常量是不能通过 Article->NAME 来进行访问的$a=new Article();echo $a::NAME; # 范围解析操作符兼容对象,找到对象所属类最终进行访问,效率降低,灵活性提高?>Class constants are fixed, while the properties of objects are different for different objects. of
静态成员
定义:使用 static 关键字修饰的类成员,表示该成员属于类访问
- 静态成员
- 静态属性
- 静态方法
- 静态成员是明确用来给类访问的,而不是对象
- 静态成员只是多了一个 static 关键字修饰,本身也可以被对象访问
- 静态成员同样可以使用不同的访问修饰限定符限定,效果一致
<?phpclass Article{ public static $name = 'hlm'; public static $type = 'art'; public static function getName() { return self::$name; }}# 静态属性$a = new Article();echo Article::$name;# 静态方法echo Article::getName();?>
self关键字
- 在类的内部(方法里面)使用,代替类名的写法
- self 如同 $this 代表内部对象一样,能够在方法内部代替当前类名
- 能够保障用户方便修改类名字
- self 关键字是代替类名,所以需要配合范围解析操作符 ::
<?phpclass Article{ public static function getInstance1() { return new self(); } public static function getInstance2() { return new Article(); }}$a = Article::getInstance1();$b = Article::getInstance2();var_dump($a,$b);?> # 输出object(Article) #1 (0) { } object(Article) #2 (0) { }
类加载
类的访问必须保证类在内存中已经存在,所以需要再用类之前将类所在的 PHP 文件加载到内存中
-
类的加载分为两种
- 手动加载:在需要使用类之间通过 include 将包含类的文件引入到内存
- 自动加载:提前定义好类结构和位置,写好引入类文件代码,在系统需要类而内存不存在的时候想办法让写好的加载类的代码执行(自动加载是自动运行写好的加载类的代码)
-
自动加载两种方式
- 魔术函数 __autoload:系统自动调用,需要传入类名,在函数内部实现类的手动加载(PHP7及之后不建议使用此方法)
function __autoload($classname){ # 找到对应的文件路径和命名规范,手动加载}
- 自定义函数:自己定义类的加载实现,然后通过 spl_autoload_register 注册到自动加载机制(可注册多个自动加载)
# 自定义类加载函数function 自定义函数($classname){ # 找到对应的文件和命名规范,手动加载}#注册自动加载sql_autoload_register('自定义函数名字')
自动加载要求在声明类的时候有良好的规范
- 类名与文件名一致:类名.php 或者 类名.class.php
- 类文件分类放好
例:手动加载
Article.php
<?phpclass Article{ public function getName(){ return __METHOD__; }}
mian.php
<?php # include 'Article.php';# 直接加载比较消耗资源,而且如果类已经在内存中存在,直接include会报错,建议判断后再加载if(!class_exists('Article')){ include 'Article.php';}$a=new Article();var_dump($a->getName()); # outputstring(16) "Article::getName"
自动加载
- __autoload(不建议使用)
一个系统中,可能类文件会放到不同的路径下,因此一个完整的自动加载函数,应该要进行文件判定功能
<?php function __autoload($classname){ # 形参代指 类名 #组织文件路径,假设当前路径下,有两个文件夹下都有类c和类m $c_file = 'c/' . $classname . '.php'; if (file_exists($c_file)) { include_once($c_file); return true; } //if 语句如果只有一行不需要加 {} //include_once 只加载一次 $m_file = 'm/' . $classname . '.php'; if (file_exists($m_file)) { include_once($m_file); return true; } } $a=new Article(); $b=new Article();
- spl_autoload_register
<?phpfunction autoload01($classname){ if(!class_exists($classname)){ $file_name=$classname.'.php'; if(file_exists($file_name)) include_once $file_name; }}spl_autoload_register('autoload01');$a=new Article();
对象克隆
通过已有的对象复制一个新的同样的对象,但两者之间并非同一个对象
面向对象高级
面向对象三大特性
封装、继承、多态
类的封装
类的继承
inherit,子类合法拥有父类的某些权限
- 继承必须满足继承关系:即存在合理的包含关系
- 继承的本质是子类通过继承可以直接使用父类已经存在的数据和数据操作
- PHP 使用 extends 关键字表示继承
子类也称派生类
父类也称基类
# 父类class Human{}# 子类继承class Man extends Human{}
类的多态
多态性是指相同的操作或函数、过程可作用于多种类型的对象上并获得不同的结果
- 需要发生类的继承,同时出现方法的重写(override),即子类拥有与父类同名的方法
- 在实例化对象的时候让父类对象指向子类对象(强制类型,PHP不支持,PHP 弱类型很灵活)
- 结果:父类对象表现的子类对象的特点
—PHP继承—
<?phpclass Human{ public function show(){ echo __METHOD__; }}class Man extends Human{}$m=new Man;$m->show();
有限继承
子类在继承父类的成员时,并非继承所有内容,而是继承并使用父类部分内容
- The essence of inheritance in PHP is object inheritance
- Inherited content in PHP: all public members, protected members and private properties of the parent class, private methods cannot be inherited
- Protected members are exclusively for inheritance and can be accessed within the parent class or subclass.
- Private members can only be accessed by setting public or protected methods in the class to which they belong
- Construction Methods and destructor methods can be inherited by subclasses,
override Override
override, subclasses define members with the same name as the parent class
parent keyword
An expression to explicitly access the members of the parent class
After the method is overridden, access the called It is a subclass method. If you want to access the parent class method, you can force access to the parent class method by using parent in the subclass method
parent cannot be used to access the properties of the parent class (static properties can)
PHP Inheritance Features
- PHP can only inherit single, there is only one parent class (if you inherit multiple classes, you can use chain inheritance)
- In PHP inheritance, there is only Private methods cannot be inherited
- PHP allows inheritance of the constructor and destructor methods in the parent class
Static delayed binding
- The interface is not a class, but it has a similar structure to the class
- The interface cannot be instantiated, but the class can implement the interface
Interface members
Interface members can only have two types- Interface constants: const
- Common interface methods (ordinary methods and static methods)
Attribute overloading
When the object accesses properties that do not exist or have insufficient permissions, the magic method is automatically triggered so that the code does not go wrong. Attribute overloading magic method- __get(attribute name): Triggered when accessing an attribute that does not exist or has insufficient permissions
- __set(attribute name, attribute value) : Triggered when setting attributes that do not exist or have insufficient permissions
- __isset(attribute name): Triggered when determining attributes that do not exist or have insufficient permissions
- __unset(attribute name): Delete non-existence or permissions Triggered when there are insufficient attributes
- __tostring(): treated as a string
method overload
object or class access does not exist or Methods with insufficient permissions, automatically triggered magic methods to make the code error-free- __cal(方法名,方法参数列表):调用不存在或者权限不够的方法时触发
- __callStatic(方法名,方法参数列表):调用不存在或者权限不够的静态方法时触发
对象遍历
将对象中的所有属性以键值对的形式取出并进行访问
对象是一种复合数据类型,对象中真正保存的内容是属性
对象的属性本质也是一种键值对关系:名字 = 值
对象遍历就是利用 foreach 对对象中的属性进行取出解析
-
对象遍历遵循访问修饰限定符的限定:即类外只能遍历所有共有属性
foreach(对象变量 as [属性名变量 =>] 属性值变量){ #属性名变量代表取出的每个属性的名字 #属性值变量代表取出的每个属性的值}
Iterator 迭代器
生成器
yield 关键字
设计模式
design pattern,是软件开发人员在软件开发过程中问题的解决方法
单例模式
singleton,是一种类的设计只会最多产生一个对象的设计思想
保证资源唯一性
工厂模式
。。。。。。
命名空间
namespace,指人为的将内存进行分隔,让不同内存区域的同名结构共存,从而解决在大型项目能出现重名结构问题
基础语法:
namespace 关键字定义空间
命名规则
字母、数字、下划线,不能以数字开头
命名空间必须写在所有代码之前,定义了一个,之后可以定义多个
子空间
subspace,即在已有空间之上,再在内部进行空间划分
子空间直接通过 namespace+路径符号 \ 实现
非限定名称
直接访问元素本身,代表当前所属空间(当前目录)
限定名称
使用空间名+原名,代表访问当前空间子空间(当前目录子目录)
完全限定名称
从根目录(全局空间)开始访问,使用 \ 作为全局空间开始符号(根目录)
全局空间元素访问:使用完全限定名称访问
命名空间引入
推荐学习:《PHP视频教程》
The above is the detailed content of Summarize the basics of PHP objects. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.