


PHP object-oriented $this keyword usage detailed explanation_PHP tutorial
This article will introduce to you students how we often use this keyword in PHP classes. Now I will briefly analyze the usage of $this keyword in object-oriented PHP. I hope this tutorial will be helpful to all students.
We knew earlier that accessing object member properties and methods outside the object is done using references to the object. Within the object, when a member method accesses other member properties or member methods in its own object, it must use a special object reference "$this->value" to access it. Which object the member belongs to, the $this reference represents. Object, and can only be used within member methods of the object.
In order to solve the naming conflict and uncertainty problem of variables and attributes in PHP classes and objects, the "$this" keyword is introduced to call the current object.
When calling the properties and methods of the current object in a class, you must use the "$this->" keyword; $this in the constructor refers to the new object created by the constructor; local variables within the method do not belong to the object. Do not use the $this keyword to obtain the value. Using the $this keyword, we can call object properties or methods in the class.
1. Call variables
Example:
代码如下 | 复制代码 |
class user{ private $n; function __construct(){ $name="Mike"; echo $this->n=$name; } } $p=new user(); ?> |
2. Call method
Example:
The code is as follows | Copy code | ||||||||
public function sum($a,$b){ Return $a+$b;
|
The code is as follows | Copy code |
class Person{
//The following are the member attributes of people
var $name; //The person’s name
var $sex; //Person’s gender
var $age; //Age of person
//Define a constructor parameter to assign values to the attributes name $name, gender $sex and age $age
function __construct($name="", $sex="", $age=""){
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}
//The way this person can speak, tell his own attributes
function say() {
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age." " ; } //Method automatically called when an object is cloned. If you want to change the contents of the original object after cloning, you need to rewrite the original object in __clone() Properties and methods of function __clone(){ //$this points to the copy p2, and $that points to the original p1, thus changing the attributes of the copy in this method. $this->name="I am fake $that->name"; $this->age=30; } } $p1=new Person("Zhang San", "Male", 20); $p2=clone $p1; $p1->say(); $p2->say(); ?> |
Output of the above example:
Execution results
My name is: Zhang San Gender: Male My age is: 20
My name is: I am the fake Zhang San Gender: Male My age is: 30
Let’s take a look at what $this does in the above code:
1. Access members inside the object, such as $this->name
2. Access other methods of the object, such as accessing the $this->run() and $this->eat("apple") methods outside the say() method.
Another thing worth noting is that local variables and member attributes can have the same name, but their scope and access methods are different. For example, $name in the eat() method body is equivalent to a local variable, and its scope is limited to eat Inside the method, $name in the member attribute declaration part of Person is equivalent to a global variable and can be accessed in other methods using the form $this->name.
Example
The code is as follows
|
Copy code | ||||
{
print( $this->name ); //The PHP keyword this pointer is used again }
TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

WebStorm Mac version
Useful JavaScript development tools
