Home Backend Development PHP Tutorial Implementing object-oriented programming in PHP_PHP tutorial

Implementing object-oriented programming in PHP_PHP tutorial

Jul 13, 2016 pm 05:19 PM
oop php introduce exist accomplish object article Demo of programming For

  这篇文章介绍在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;
 }
}

?>

本新闻共4页,当前在第1页  1  2  3  4  

 所以可以用如下方法创建对象:

$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(); // x=3 and y=5
$obj=new Something(8); // x=8 and y=5
$obj=new Something(8,9); // x=8 and y=9
$obj=new Something(8); // x=8 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;
}
}

?>
Overloading is not supported in PHP. In object-oriented programming, you can overload a member function with the same name by defining different parameter types and numbers. PHP is a loosely typed language, so parameter type overloading is useless. Similarly, overloading with different number of parameters will not work.

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;

}

} ?>
The purpose of overloading can be partially achieved through this method.

TABLE>

This news has a total of pages, currently on page 2 1 2 3 4
Polymorphism
Polymorphism is defined as when an object is passed as a parameter at run time, the object can decide which method to call. ability. For example, a class defines the method "draw", and the inherited class redefines the behavior of "draw" to draw a circle or a square, so that you have a function with a parameter of x, in which you can call $x->draw() . If polymorphism is supported, the call to the "draw" method depends on the type of object x. Polymorphism is naturally supported in PHP (think of this situation http://www.bkjia.com/PHPjc/532649.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/532649.htmlTechArticleThis article introduces object-oriented programming (OOP) in PHP. I'll demonstrate how to use object-oriented concepts to write better programs with less code. Good luck to everyone. The concept of object-oriented programming...
$obj1=new Myclass(1); //Will call Myclass1 $obj2=new Myclass(1,2); //Will call Myclass2
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

See all articles