Home > Backend Development > PHP Tutorial > Introduction to object-oriented knowledge for PHP interviews

Introduction to object-oriented knowledge for PHP interviews

不言
Release: 2023-04-05 07:52:01
forward
6379 people have browsed it

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();
?>
Copy after login

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(){
    /* 类的初始化代码*/
}
Copy after login

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

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

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

在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!

source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template