search
HomeBackend DevelopmentPHP TutorialIntroduction to object-oriented knowledge for PHP interviews

Introduction to object-oriented knowledge for PHP interviews

Feb 13, 2019 pm 03:20 PM
oopphpobject-oriented design patternsinterview

The content of this article is an introduction to object-oriented knowledge about PHP interviews. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The common object-oriented knowledge points in PHP are the following 7 points. I will introduce the following points in detail to help you better cope with the object-oriented knowledge points that are frequently tested in PHP interviews. Exam questions.

Related recommendations: "2019 PHP Interview Questions Summary (Collection)"

The content modules involved in the structure of the entire object-oriented article are:

1. What is the difference between object-oriented and process-oriented?
2. What are the characteristics of object-oriented?
3. What are constructors and destructors?
4. What are the types of object-oriented scopes?
5. What are the magic methods in PHP?
6. What is object cloning?
7. What is the difference between this, self and parent?
8. What are the differences and connections between abstract classes and interfaces?
9. Explanation of common PHP object-oriented interview questions

The content about PHP object-oriented will be divided into three articles to explain the complete content. One article mainly explains the content from one to four points, the second article mainly explains the content from five to eight points, and the third article focuses on the ninth point.

The content of the following text comes from the "PHP Programmer Interview Written Test Guide" book. If you reprint, please keep the source:

1. Object-oriented and process-oriented What's the difference?

Object-oriented is one of the mainstream methods of today's software development methods. It puts data and data manipulation methods together as an interdependent whole, that is, an object. Abstract the common features of similar objects, that is, classes. Most of the data in the class can only be processed by the methods of this class. The class relates to the outside world through a simple external interface, and objects communicate through messages. The program flow is determined by the user during use. For example, from an abstract perspective, humans have special names such as height, weight, age, blood type, etc. Human beings can work, walk upright, eat, and use their own minds to create tools. Human beings are just an abstraction. It is a non-existent entity, but all objects that have the attributes and methods of the human group are called people. This object person is an entity that actually exists, and everyone is an object of the human group.
Process-oriented is an event-centered development method, which is executed sequentially from top to bottom and gradually refined. Its program structure is divided into several basic modules according to functions. These modules form a tree structure. The relationship between each module is relatively simple and relatively independent in function. Each module is generally composed of three basic structures: sequence, selection and loop. The specific method of modular implementation is to use subroutines, and the program flow This is decided when writing the program. For example, in backgammon, the process-oriented design idea is to first analyze the steps of the problem: the first step, start the game; the second step, the black stone moves first; the third step, draw the picture; the fourth step, judge the winner or lose; the fifth step, it is the turn White; Step 6, draw the picture; Step 7, determine the winner or lose; Step 8, return to step 2; Step 9, output the final result. Implementing each of the above steps with separate functions is a process-oriented development method.

Specifically, the two mainly differ in the following aspects.
1) The starting point is different. Object-oriented is to use conventional thinking methods to deal with problems in the objective world, emphasizing the direct mapping of the key points of the problem domain to objects and the interfaces between objects. This is not the case with the process-oriented method. It emphasizes the abstraction and modularization of the process. It constructs or handles objective world problems with the process as the center.
2) The hierarchical logical relationships are different. The object-oriented method uses computer logic to simulate the physical existence in the objective world, using the collection class of objects as the basic unit for processing problems, and tries to make the computer world as close to the objective world as possible, so that the problem processing can be made clearer Directly, the object-oriented method uses the class hierarchy to reflect the inheritance and development between classes. The basic unit of process-oriented method to deal with problems is a module that can clearly and accurately express the process. The hierarchical structure of the module is used to summarize the relationships and functions between modules or modules, and the problems in the objective world are abstracted into processes that can be processed by computers.
3) The data processing method is different from the control program method. The object-oriented method encapsulates the data and the corresponding code into a whole. In principle, other objects cannot modify their data directly, that is, the modification of the object can only be completed by its own member functions. The control program is "event-driven" to activate and run the program. The process-oriented method processes data directly through the program, and the processing results can be displayed after the processing is completed. In the control program method, the program is called or returned according to the design, and cannot be freely navigated. There are controls, controlled, and calls between each module. with being called.
4) Analysis design and coding conversion methods are different. The object-oriented method is a smooth process throughout the software life cycle between analysis, design and coding. From analysis to design to coding, a consistent model is used, that is, a seamless connection is achieved. The process-oriented method emphasizes the transformation between analysis, design and coding according to rules, and achieves a seamless connection between analysis, design and coding throughout the software life cycle.

2. What are the characteristics of object-oriented?


#The main features of object-oriented are abstraction, inheritance, encapsulation and polymorphism.

1) Abstraction. Abstraction is to ignore those aspects of a topic that are irrelevant to the current goal in order to pay more full attention to aspects that are relevant to the current goal. Abstraction does not intend to understand the entire problem, but only selects a part of it and leaves out some details for the time being. Abstraction includes two aspects, one is process abstraction, and the other is data abstraction.

2) Inheritance. Inheritance is a hierarchical model that connects classes and allows and encourages the reuse of classes. It provides a way to clearly express commonalities. A new class of an object can be derived from an existing class, a process called class inheritance. The new class inherits the characteristics of the original class. The new class is called the derived class (subclass) of the original class, and the original class is called the base class (parent class) of the new class. A derived class can inherit methods and instance variables from its base class, and subclasses can modify or add new methods to better suit special needs.
3) Encapsulation. Encapsulation refers to abstracting objective things into classes, and each class protects its own data and methods. Classes can allow only trusted classes or objects to operate their data and methods, and hide untrusted information.
4) Polymorphism. Polymorphism refers to allowing objects of different types to respond to the same message. Polymorphism includes parameterized polymorphism and contained polymorphism. Polymorphic languages ​​have the advantages of flexibility, abstraction, behavior sharing, and code sharing, and can well solve the problem of application functions with the same name.

3. What are constructors and destructors?

1. Constructor

In versions before PHP5, the name of the constructor must be the same as the name of the class. Starting from PHP5, developers can define a method named __construct as the constructor. The function of the constructor is to be automatically called when the class is instantiated, so the constructor is mainly used to do some initialization work. One advantage of using __construct as the name of the constructor is that when the class name is modified, the name of the constructor does not need to be modified. Its declaration form is
void __construct ([ mixed $args [, $... ]] )

In C language, the constructor of the subclass will implicitly call the parameterless function of the parent class 's constructor. However, in PHP, the constructor of a subclass will not implicitly call the constructor of the parent class. Developers need to explicitly call the constructor of the parent class through parent::__construct(). When a subclass does not define a constructor, it will inherit the constructor of the parent class, but the premise is that the constructor of the parent class cannot be defined as private. Usage examples are as follows:

<?php     
    class BaseClass {
        function __construct() {
            print "Base constructor\n";
        }
    }
    class SubClass extends BaseClass {
        function __construct() {
            parent::__construct();
            print "Sub constructor\n";
        }
    }
    // 会调用父类构造函数
    $obj = new BaseClass();
    //调用子类构造函数,子类构造函数会去调用父类构造函数
    $obj = new SubClass();
?>

The running result of the program is

Base constructor
Base constructor
Sub constructor

从上面的讲解中可以发现,从PHP5开始多了一种构造函数定义的方法。为了实现不同版本PHP代码的兼容,在PHP5的类中找不到 __construct() 函数并且也没有从父类继承一个的话,那么它就会尝试寻找旧式的构造函数(与类同名的函数)。这种兼容的方法存在一个风险:在PHP5之前的版本中开发的类中已有一个名为 __construct() 的方法却被用于其他用途时,PHP5的类会认为这是一个构造函数,从而当类实例化时自动执行这个方法。
从 PHP 5.3.3 开始,在命名空间中,与类名同名的方法不再作为构造函数。这一改变不影响不在命名空间中的类。

2.析构函数

析构函数是在PHP5引入的,它的作用与调用时机和构造函数刚好相反,它在对象被销毁时自动执行。析构函数__destruct()结构形式如下:

function __destruct(){
    /* 类的初始化代码*/
}

需要注意的是,析构函数是由系统自动调用的,因此,它不需要参数。
默认情况下,系统仅释放对象属性所占用的内存,并不销毁在对象内部申请的资源(例如,打开文件、创建数据库的连接等),而利用析构函数在使用一个对象之后执行代码来清除这些在对象内部申请的资源(关闭文件、断开与数据库的连接)。
与构造函数类似,如果想在子类中调用父类的析构函数,那么需要显式地调用:parent::__destruct()。如果子类没有定义析构函数,那么它会继承父类的析构函数。
当对象不再被引用时,将调用析构函数。如果要明确地销毁一个对象,那么可以给指向对象的变量不分配任何值,通常将变量赋值为NULL或者用unset()函数。示例代码如下:

<?php  
    class des{
        function __destruct(){
            echo "对象被销毁,执行析构函数<br>";
        }
    }
    $p=new des(); /* 实例化类 */
    echo "程序开始<br>";
    unset($p); /* 销毁变量$p */
    echo "程序结束";
?>

四、面向对象的作用域范围有哪几种?

在PHP5中,类的属性或者方法主要有public、protected和private三种类作用域,它们的区别如下:
1)public(公有类型)表示全局,类内部、外部和子类都可以访问。
默认的访问权限为public,也就是说,如果一个方法没有被public、protected或private修饰,那么它默认的作用域为public。
2)protected(受保护类型)表示受保护的,只有本类或子类可以访问。
在子类中,可以通过self::var或self::method访问,也可以通过parent::method来调用父类中的方法。
在类的实例化对象中,不能通过$obj->var来访问protected类型的方法或属性。
3)private(私有类型)表示私有的,只有本类内部可以使用。
该类型的属性或方法只能在该类中使用,在该类的实例、子类、子类的实例中都不能调用私有类型的属性和方法。


The above is the detailed content of Introduction to object-oriented knowledge for PHP interviews. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

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: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

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 and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

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.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

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 and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

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.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

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

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

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