Implementing object-oriented programming in PHP_PHP tutorial
这篇文章介绍在PHP的面向对象编程(OOP)。我将演示如何用面向对象的概念编出较少的代码但更好的程序。祝大家好运。
面向对象编程的概念对每一个作者来说都有不同的看法,我提醒一下一个面向对象语言应有的东西:
- 数据抽象和信息隐藏
- 继承
- 多态性
在PHP中使用类进行封装的办法:
class Something {
// In OOP classes are usually named starting with a cap letter.
var $x;
function setX($v) {
// Methods start in lowercase then use lowercase to seprate
// words in the method name example getValueOfArea()
$this->x=$v;
}
function getX() {
return $this->x;
}
}
?>
当然你可以用你自己的办法,但有一个标准总是好的。
PHP中类的数据成员使用 "var" 定义,数据成员是没有类型直到被赋值。一个数据成员可能是一个 integer、数组、联合数组(associative array)或甚至对象(object). 方法在类里定义成函数,在方法里存取数据成员,你必须使用$this->name 这样的办法,否则对方法来说是一个函数的局部变量。
使用 new 来创建一个对象
$obj = new Something;
然后使用成员函数
$obj->setX(5);
$see = $obj->getX();
setX 成员函数将 5 赋给对象(而不是类)obj 中成员变量, 然后 getX 返回值 5.
你也可以用对象引用来存取成员变量,例如:$obj->x=6; 然而,这不一种好的面向对象编程的方法。我坚持你应使用成员函数来设置成员变量的值和通过成员函数来读取成员变量。如果你认为成员变量是不可存取的除了使用成员函数的办法,你将成为一个好的面向对象程序员。 但不幸的是PHP本身没有办法声明一个变量是私有的,所以允许糟糕的代码存在。
在 PHP 中继承使用 extend 来声明。
class Another extends Something {
var $y;
function setY($v) {
// Methods start in lowercase then use lowercase to seperate
// words in the method name example getValueOfArea()
$this->y=$v;
}
function getY() {
return $this->y;
}
}
?>
这样类 "Another" 的对象拥有父类的所用成员变量及方法函数,再加上自己的成员变量及成员函数。如:
$obj2=new Another;
$obj2->setX(6);
$obj2->setY(7);
多重继承不被支持,所以你不能让一个类继承多个类。
在继承类中你可以重新定义来重定义方法,如果我们在 "Another" 重新定义 getX,那么我们不再能存取 "Something" 中的成员函数 getX. 同样,如果我们在继承类中声明一个和父类同名的成员变量,那么继承类的变量将隐藏父类的同名变量。
你可以定义一个类的构造函数, 构造函数是和类同名的成员函数,在你创建类的对象时被调用。
class Something {
var $x;
function Something($y) {
$this->x=$y;
}
function setX($v) {
$this->x=$v;
}
function getX() {
return $this->x;
}
}
?>
所以可以用如下方法创建对象:
$obj=new Something(6); |
构造函数自动赋值 5 给成员变量 x, 构造函数和成员函数都是普通的PHP函数,所以你可以使用缺省参数。
function Something($x="3",$y="5") |
Then:
$obj=new Something(); // x=3 and y=5
$obj=new Something( 8,9); // x=8 and y=9 |
The default parameter is defined in the same way as C++, so you cannot pass a value to Y But let X take the default value, the arguments are passed from left to right, and the function will use the default arguments when there are no more arguments.
Only when the constructor of the inherited class is called, the object of the inherited class is created, and the constructor of the parent class is not called. This is a feature of PHP that is different from other object-oriented languages, because the constructor call chain It is a characteristic of object-oriented programming. If you want to call the base class's constructor, you have to call it explicitly in the inheriting class's constructor. This works because all methods of the parent class are available in the inherited class.
function Another() { $this->y=5; $this->Something(); //explicit call to base class constructor. } ?> |
function Another() { $this->y=5; $this->Something(); //explicit call to base class constructor. } ? > |
A good mechanism in object-oriented programming is to use abstract classes. An abstract class is a class that cannot be instantiated but is used to inherit classes. Class that defines the interface. Designers often use abstract classes to force programmers to only inherit from a specific base class, so they can be sure that the new class has the required functionality, but there is no standard way to do this in PHP, however:
If you need this feature when defining a base class, you can do so by calling "die" in the constructor. This way you can ensure that it cannot be instantiated. Now define the functions of the abstract class and call "die" in each function. ",If the programmer directly calls the base class function in the inherited class without redefining it, an error will occur.
Additionally, you need to make sure that since PHP has no types, some objects are created from inherited classes that inherit from the base class, so add a method in the base class to identify the class (return "some identity") and verify This comes in handy when you receive an object as a parameter. But there is no solution for a rogue program, because he can redefine this function in the inherited class, usually this method only works for lazy programmers. Of course, the best way is to prevent the program from touching the base class code and only provide the interface.
class Myclass { function Myclass() { $name="Myclass".func_num_args(); $this->$name(); //Note that $this->$name() is usually wrong but here //$name is a string with the name of the method to call. } function Myclass1($x) { code; } function Myclass2($x,$y) { code; } } ?> |
Sometimes it is useful in object-oriented programming to overload constructors so you can create different objects in different ways (by passing a different number of arguments). A small door can do this:
$obj1=new Myclass(1); //Will call Myclass1 $obj2=new Myclass(1,2); //Will call Myclass2 |
class Myclass { function Myclass() { $name="Myclass".func_num_args(); $this->$name(); //Note that $this- >$name() is usually wrong but here //$name is a string with the name of the method to call. } function Myclass1($x) { code ; } function Myclass2($x,$y) { code; } } ?> |
$obj1=new Myclass(1); //Will call Myclass1 $obj2=new Myclass(1,2); //Will call Myclass2 |

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

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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 is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

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.
