Home Backend Development PHP Tutorial How to instantiate objects in PHP object-oriented (OOP)?

How to instantiate objects in PHP object-oriented (OOP)?

Apr 19, 2019 pm 01:33 PM
php object-oriented

The unit of an object-oriented program is an object, but an object is instantiated by a class. Now that our class has been declared, the next step is to instantiate the object. Below we will introduce to you how to instantiate objects.

How to instantiate objects in PHP object-oriented (OOP)?

After defining the class, we use the new keyword to generate an object.

$Object name = new class name();


<?php
class Person
{
    //下面是人的成员属性
    var $name; //人的名字
    var $sex; //人的性别
    var $age; //人的年龄
 
    //下面是人的成员方法
    function say() { //这个人可以说话的方法
        echo "这个人在说话";
    }
 
    function run() { //这个人可以走路的方法
        echo "这个人在走路";
    }
}
 
$p1=new Person();
$p2=new Person();
$p3=new Person();
?>
Copy after login

$p1=new Person();

This code is the process of generating instance objects through classes. $p1 is the name of the object we instantiate. Similarly, $p2 and $p3 are also the names of the objects we instantiate. A class can be instantiated. Multiple objects are generated, each object is independent. The above code is equivalent to the example of 3 people. There is no connection between each person. It can only mean that they are all human beings. Each person has his own name and gender. and age attributes, everyone has a way of talking and walking. As long as the member attributes and member methods are reflected in the class, the instantiated object will contain these attributes and methods.

Objects in PHP are also a data class like integers and floating point types. They are used to store different types of data and must be loaded into memory during operation. , So how are objects reflected in memory?

Memory is generally divided into 4 segments logically, stack space segment, heap space segment,code segment, Initialization of static segment ,

①.Stack space segment

The stack is characterized by small space but fast access by the CPU. It is temporarily created by the user to store the program. variable. Due to the last-in-first-out nature of the stack, the stack is particularly convenient for saving and restoring call scenes. In this sense, we can think of the stack as a memory area for temporary data storage and exchange. Memory segments used to store data types that occupy a constant length and a small space. For example, integers 1, 100, 10000, etc. occupy the same length of space in the memory, and the space occupied is 32-bit and 4 bytes. Double, boolean, etc. can also be stored in the stack space segment.

②. Heap space segment

The heap is used to store the memory segment that is dynamically allocated during the running of the process. Its size is not fixed and can be dynamically expanded or reduced. Used to store data with variable data length or large memory usage. For example, strings, arrays, and objects are stored in this memory.

③. Data segment

The data segment is used to store initialized global variables in the executable file. In other words, it stores variables statically allocated by the program.

④.Code segment

The code segment is used to store the operation instructions of the executable file, which means that it is the image of the executable program in the memory. The code segment needs to be prevented from being illegally modified at runtime, so only read operations are allowed, but write (modification) operations are not allowed. For example, the functions in the program are stored in this memory.

Object type data is a data type that occupies a relatively large space, and it is a data type that occupies a variable length of space. Therefore, after the object is created, it is stored in the memory, but the reference to the object is still stored. inside the stack. When the program is running, the data in the memory can be directly accessed, while the heap memory is memory that cannot be directly accessed, but the members in the object can be accessed through the reference name of the object.

Different declarations in the program are placed in different memory segments.

The stack space segment occupies the same space length and takes up less space. The data types, such as integers 1, 10, 100, 1000, 10000, 100000, etc., occupy the same length of space in the memory, and are all 64 bits and 4 bytes.

Then the data length is variable and the data type that occupies a large space is placed in which segment of the memory? Such data is placed in the heap memory.

Stack memory can be directly accessed, but heap memory cannot be directly accessed.

For our object, it is a large data type and it takes up space of a variable length, so the object is placed in the heap, but the object name is placed in the stack. , so that the object can be used through the object name.

$p1=new Person();

For this code, $p1 is the object name in the stack memory, new Person() is the real object in the heap memory Inside, please see the picture below for details:

How to instantiate objects in PHP object-oriented (OOP)?

从上图可以看出$p1=new Person();等号右边是真正的对象实例, 在堆内存里面的实体,上图一共有3次new Person(),所以会在堆里面开辟3个空间,产生3个实例对象,每个对象之间都是相互独立的,使用自己的空间,在PHP里面,只要有一个new这个关键字出现就会实例化出来一个对象,在堆里面开辟一块自己的空间。

每个在堆里面的实例对象是存储属性的,比如说,现在堆里面的实例对象里面都存有姓名、性别和年龄。每个属性又都有一个地址。

$p1=new Person();等号的左边$p1是一个引用变量,通过赋值运算符“=”把对象的首地址赋给“$p1“这个引用变量, 所以$p1是存储对象首地址的变量,$p1放在栈内存里边,$p1相当于一个指针指向堆里面的对象, 所以我们可以通过$p1这个引用变量来操作对象, 通常我们也称对象引用为对象。

验证:

class Person{
  public $name;
}

$obj1 = new Person();
$obj1->name = "test1";
echo $obj1->name;
$obj2 = $obj1;
$obj2->name = "test2";
echo $obj1->name;
echo $obj2->name;
Copy after login

通过测试结果来看,解释是对的。

$p1 是对象的指针而不是对象本身 obj2obj1都指向同一块内存同一个对象这一点和OOP语言是一样

object(Person)[2] 
public &#39;name&#39; => string &#39;test2&#39; (length=5)
Copy after login
object(Person)[2]
public &#39;name&#39; => string &#39;test2&#39; (length=5)
Copy after login

可见对象的ID号是一个

如果想得到一个对象的副本,用$obj2 =clone $obj1; 用了clone后会产生一个新对象,分配内存,独立于原来的obj1
参见手册此页 http://www.php.net/manual/zh/language.oop5.cloning.php

$obj2 = $obj1;
$obj2 = &$obj1;
Copy after login

一样的效果,一样的解释?
对于object来说,是一样的。 对于普通的变量是不一样的。

$a = 1;
$b = $a;
$c = &$a;
Copy after login

不一样的 

The above is the detailed content of How to instantiate objects in PHP object-oriented (OOP)?. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

An in-depth explanation of PHP's object-oriented encapsulation An in-depth explanation of PHP's object-oriented encapsulation Aug 11, 2023 am 11:00 AM

In-depth interpretation of PHP object-oriented encapsulation Encapsulation is one of the three major characteristics of object-oriented programming. It refers to encapsulating data and operations on data in a class, hiding specific implementation details from external programs, and providing external interfaces. In PHP, the concept of encapsulation is implemented by using access modifiers (public, protected, private) to control the accessibility of properties and methods. First, let’s take a look at the role of access modifiers: public (public): Public properties and methods can

How to implement object version control and management through PHP object-oriented simple factory pattern How to implement object version control and management through PHP object-oriented simple factory pattern Sep 06, 2023 pm 02:39 PM

How to implement object version control and management through the PHP object-oriented simple factory model. When developing large and complex PHP projects, version control and management are very important. Through appropriate design patterns, we can better manage and control the creation and use of objects, thereby improving the maintainability and scalability of the code. This article will introduce how to use the PHP object-oriented simple factory pattern to implement object version control and management. The simple factory pattern is a design pattern for creating classes that instantiates specified objects through a factory class

How to achieve seamless switching and replacement of objects through PHP object-oriented simple factory pattern How to achieve seamless switching and replacement of objects through PHP object-oriented simple factory pattern Sep 06, 2023 am 08:01 AM

How to achieve seamless switching and replacement of objects through PHP's object-oriented simple factory pattern Introduction: In PHP development, object-oriented programming (Object-oriented Programming, referred to as OOP) is a very common programming paradigm. The object-oriented design pattern can further improve the maintainability and scalability of the code. This article will focus on the simple factory pattern in PHP to achieve seamless switching and replacement of objects. What is the simple factory pattern? Simple factory pattern (Simple

How to create flexible object instances using PHP object-oriented simple factory pattern How to create flexible object instances using PHP object-oriented simple factory pattern Sep 06, 2023 pm 02:12 PM

How to create flexible object instances using the PHP object-oriented simple factory pattern. The simple factory pattern is a common design pattern that creates object instances without exposing object creation logic. This mode can improve the flexibility and maintainability of the code, and is especially suitable for scenarios where different objects need to be dynamically created based on input conditions. In PHP, we can use the characteristics of object-oriented programming to implement the simple factory pattern. Let's look at an example below. Suppose we need to create a graphing calculator that can

How to master object-oriented programming skills in PHP development How to master object-oriented programming skills in PHP development Jun 25, 2023 am 08:05 AM

With the development of the Internet, PHP has gradually become one of the most popular programming languages ​​​​in web development. However, with the rapid development of PHP, object-oriented programming has become one of the necessary skills in PHP development. In this article, we will discuss how to master object-oriented programming skills in PHP development. Understanding the Concepts of Object-Oriented Programming Object-oriented programming is a programming paradigm that organizes code and data through the use of objects (classes, properties, and methods). In object-oriented programming, code is organized into reusable modules, thereby improving the program's

Understand the object-oriented inheritance mechanism of PHP Understand the object-oriented inheritance mechanism of PHP Aug 10, 2023 am 10:40 AM

Understanding the Object-Oriented Inheritance Mechanism of PHP Inheritance is an important concept in object-oriented programming, which allows the creation of new classes that include the features and functionality of the old classes. In PHP, inheritance can be achieved through the keyword extends. Through inheritance, subclasses can inherit the properties and methods of the parent class, and can add new properties and methods, or override inherited methods. Let us understand the object-oriented inheritance mechanism of PHP through an example. classAnimal{public$name

How PHP implements object-oriented programming and improves code readability and maintainability How PHP implements object-oriented programming and improves code readability and maintainability Jun 27, 2023 pm 12:28 PM

With the continuous development of Internet technology, PHP has become one of our common website development languages, and PHP object-oriented programming has also become a knowledge point that must be learned. Object-oriented programming (OOP) is a programming paradigm whose core concept is to combine data and behavior into an object to improve code reusability, readability, and maintainability. This article will explore how to use PHP to implement object-oriented programming and improve the readability and maintainability of your code. Basic Concepts of Object-Oriented Programming In object-oriented programming, each object has a set of properties.

Detailed explanation of common problems in PHP object-oriented programming Detailed explanation of common problems in PHP object-oriented programming Jun 09, 2023 am 09:27 AM

PHP language has become a very popular web development language because it is easy to learn and use. Object-oriented programming is one of the most important programming paradigms in the PHP language. However, object-oriented programming is not something that is easy to master, so some common problems often arise. In this article, we will provide a detailed analysis of common problems with object-oriented programming in PHP. Question 1: How to create an object? In PHP, you can use the new keyword to create an object. For example: classMyClass{/

See all articles