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.
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(); ?>
$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:
从上图可以看出$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;
通过测试结果来看,解释是对的。
$p1 是对象的指针而不是对象本身, obj2和 obj1都指向同一块内存,同一个对象。这一点和OOP语言是一样
object(Person)[2] public 'name' => string 'test2' (length=5)
object(Person)[2] public 'name' => string 'test2' (length=5)
可见对象的ID号是一个
如果想得到一个对象的副本,用$obj2 =clone $obj1; 用了clone后会产生一个新对象,分配内存,独立于原来的obj1
参见手册此页 http://www.php.net/manual/zh/language.oop5.cloning.php
$obj2 = $obj1; $obj2 = &$obj1;
一样的效果,一样的解释?
对于object来说,是一样的。 对于普通的变量是不一样的。
$a = 1; $b = $a; $c = &$a;
不一样的
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!

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.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor