The first intimate contact with PHP5(1)_PHP tutorial
Article source: PHPBuilder.com
Original author: Luis Argerich
Translation: erquan
erquan Note: I haven’t had time to experience PHP5 yet, so I just translated an article written by a foreigner.
The following are all translated by erquan. I hope this is the first time I have done this and it has not misled anyone. Please understand some inaccuracies.
Let’s see if this works. If it works, I’ll finish the translation. If it doesn’t, I’ll just translate it, so as not to mislead everyone, which is also tiring. . . . :)
Please indicate the source of the article when reposting, thank you:)
The official version of PHP5 has not been released yet, but we can learn and experience the new PHP features brought to us by the development version .
This article will focus on the following 3 new PHP5 features:
* New Object Mode
* Structured Exception Handling
* Namespace
Before officially starting, please note:
*Some examples in the article are implemented using PHP4, just to enhance the readability of the article
*The new features described in this article may be different from the features of the official version, please refer to the official version.
* New Object Mode
The new object mode of PHP5 has been greatly "upgraded" based on PHP4. You will look a lot like JAVA: (.
Some of the following text will do it Some brief introductions, with small examples to help you start experiencing the new features of PHP5
come on~~:)
* Constructors and destructors
* Object references
* Clone object
* 3 modes of objects: private, public and protected
* Interface
* Virtual class
* __call()
* __set() and __get()
* Static members
Constructor and destructor
In PHP4, a function with the same name as a class is defaulted to the constructor of the class, and there is no concept of a destructor in PHP4. (Erquan's note: This is the same as JAVA)
But starting from PHP5, the constructor is uniformly named __construct, and there is a destructor: __destruct (Erquan's note: This is the same as Delphi. It can be seen that PHP5 Congratulations for absorbing many mature OO ideas~~):
Example 1: Constructor and destructor
class foo {
var $ x;
function __construct($x) {
$this->x = $x;
}
function display() {
print($this ->x);
}
function __destruct() {
print("bye bye");
}
}
$o1 = new foo(4);
$o1->display();
?>
After running, you will see "bye bye" output. This is because the class terminates The __destruct() destructor was called~~
Object reference
As you know, in PHP4, when passing a variable to a function or method, a copy is actually passed, unless you use the address operator & to declare
You are making a reference to a variable. In PHP5, objects are always specified by reference:
Example 2: Object reference
class foo {
var $x;
function setX($x) {
$this->x = $x;
}
function getX() {
return $this->x;
}
}
$o1 = new foo;
$o1->setX(4);
$o2 = $o1;
$o1->setX( 5);
if($o1->getX() == $o2->getX()) print("Oh my god!");
?>
( Erquan's note: You will see the output of "Oh my god!")
Clone object
is as above. What should I do if sometimes I don’t want to get a reference to the object and want to use copy? Implemented in the __clone method provided by PHP5:
Example 3: Clone object
class foo {
var $x;
function setX( $x) {
$this->x = $x;
}
function getX() {
return $this->x;
}
}
$o1 = new foo;
$o1->setX(4);
$o2 = $o1->__clone();
$o1->setX (5);
if($o1->getX() != $o2->getX()) print("Copies are independant");
?>
The method of cloning objects has been used in many languages, so you don’t have to worry about its performance :).
Private, Public and Protected
In PHP4, you can operate any of its methods and variables from outside the object - because the methods and variables are public.Three modes are cited in PHP5 to control
control permissions on variables and methods: Public (public), Protected (protected) and Private (private)
Public: methods and variables can be used anywhere When accessed
Private: can only be accessed inside the class, nor can it be accessed by subclasses
Protected: can only be accessed inside the class or subclasses
Example 4: Public, protected and private
class foo {
private $x;
public function public_foo() {
print("I'm public ");
}
protected function protected_foo() {
$this->private_foo(); //Ok because we are in the same class we can call private methods
print ("I'm protected");
}
private function private_foo() {
$this->x = 3;
print("I'm private");
}
}
class foo2 extends foo {
public function display() {
$this->protected_foo();
$this->public_foo( );
// $this->private_foo(); // Invalid! the function is private in the base class
}
}
$x = new foo();
$x->public_foo();
//$x->protected_foo(); //Invalid cannot call protected methods outside the class and derived classes
//$x->private_foo (); //Invalid private methods can only be used inside the class
$x2 = new foo2();
$x2->display();
?>
Tip: Variables are always private. Directly accessing a private variable is not a good OOP idea. You should use other methods to implement set/get functions
Interface
As you know, the syntax for implementing inheritance in PHP4 is "class foo extends parent". No matter in PHP4 or PHP5, multiple inheritance is not supported, that is, you can only inherit from one class. The "interface" in PHP5 is a special class: it does not specifically implement a method, but is used to define the name of the method and the elements it owns, and then reference them together through keywords to implement specific actions.
Example 5: Interface
interface displayable {
function display();
}
interface printable {
function doprint( );
}
class foo implements displayable,printable {
function display() {
// code
}
function doprint() {
// code
}
}
?>
This is very helpful for the reading and understanding of the code: when you read this class, you know that foo contains The interfaces displayable and printable are provided, and there must be print() (Erquan's note: it should be doprint()) method and display() method. You can easily manipulate them without knowing how they are implemented internally as long as you see the declaration of foo.
Virtual class
A virtual class is a class that cannot be instantiated. It can define methods and variables like a super class.
Virtual methods can also be defined in virtual classes, and this method cannot be implemented in this class, but must be implemented in its subclasses
Example 6: Virtual class
abstract class foo {
protected $x;
abstract function display();
function setX($x) {
$ this->x = $x;
}
}
class foo2 extends foo {
function display() {
}
}
?>
__call() method
In PHP5, if you define the __call() method, __call() will be automatically called when you try to access a non-existent variable or method in the class:
Example 7: __call
class foo {
function __call($name,$arguments) {
print("Did you call me ? I'm $name!");
}
}
$x = new foo();
$x->doStuff();
$x- >fancy_stuff();
?>
This particular method is customarily used to implement "method overloading" because you rely on a private parameter to implement and check this parameter:
Exampe 8: __call implements method overloading
class Magic {
function __call($name,$arguments) {
if($name= ='foo') {
if(is_int($arguments[0])) $this->foo_for_int($arguments[0]);
if(is_string($arguments[0])) $this ->foo_for_string($arguments[0]);
}
}
private function foo_for_int($x) {
print("oh an int!");
}
private function foo_for_string($x) {
print("oh a string!");
}
}
$x = new Magic();
$x->foo(3);
$x->foo("3");
?>
__set() method and __get() method
When accessing or setting an undefined variable, these two methods will be called:
Example 9: __set and __get
class foo {
function __set($name,$val) {
print("Hello, you tried to put $val in $name");
}
function __get($name) {
print("Hey you asked for $name");
}
}
$x = new foo ();
$x->bar = 3;
print($x->winky_winky);
?>

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development 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.

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool