


Why do you need to use a constructor to initialize global variables when writing a class in PHP?
I know the question I asked is very basic, but this is where I have questions
class car{ private $name; private $num; public function __construct($name,$num){ $this->name=$name; $this->num=$nau; } }
Why do you write it like this? $this->name=$name;
Why initialize global variables;
Reply content:
I know the question I asked is very basic, but this is where I have questions
class car{ private $name; private $num; public function __construct($name,$num){ $this->name=$name; $this->num=$nau; } }
Why do you write it like this? $this->name=$name;
Why initialize global variables;
<code> 这个问题有点像多态: class User { public $user_name; public $age; public function __construct($user_name,$age) { $this->user_name = $user_name; $this->age = $age; } } $obj1 = new User('张三',28); //用户1 $obj2 = new User('张思','22'); //用户2 //看到没有?构造的好处,你一个用户类,不用改动任何代码就能实现多态,每次new的时候传不同的参数 </code>
There is no why, no need to question, it’s just that you write it like this when you use it.
1- There is no requirement that a class must have a constructor
2- There is also no requirement that attributes must be initialized during construction
For example
<code>class Car { private $color = 'Blue'; private $band = 'Audi'; public function set($attr, $value) { $this->$attr = $value; return $this; } } $car = new Car(); $car->set('color', 'red')->set('band', 'BMW');</code>
There is no difference between writing this way and how you write it, it just needs to be changed accordingly when using it. So, the answer to your question is: the person who wrote the code thought it was good, and then they wrote it.
Otherwise, when will it be initialized?
$name
is just a local variable and cannot be accessed after __construct
is removed.
Thanks for the invitation. . But I’m not very clear about anything too specific
__construct is the construction method
It is the method that is executed first when instantiating a class
The two parameters of __construct are passed in during instantiation
For examplenew car ($name,$num);
After instantiation like this, the $name and $num variables become private variables of the car class
Convenient to call by the class itself. . .
As for $this, it is equivalent to the class itself. $this-> can then call the methods or properties of the class itself
It is better to read the official manual first
http://php.net/manual/zh/language.oop5.basic.php
Usually in the constructor, initialize member variables and instantiate classes used by many member methods (it is clearer to write code this way, but some classes are only used once, and it is not recommended to instantiate them in the constructor, which affects program performance)
Well, actually when I first started using php
, I didn’t know why I used it this way. There is no such thing as a low-level question, just ask if you are not sure. The function of the constructor is that every time you create a new object, you will first call this method. In fact, to put it bluntly, it is the function of initialization. Hope it helps you

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

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