Home php教程 php手册 php面向对象编程学习笔记

php面向对象编程学习笔记

Jun 13, 2016 am 10:16 AM
php Instructions study object article yes use notes programming For

面向对象编程是php中一种常用的使用方法,本文章来介绍php面向对象简单使用方法与一些基本知识有需要的朋友可进入参考。

(OOP)来开发。面向对象开发相对于面向过程有很多优点:
维护简单   模块化是面向对象编程中的一个特征。实体被表示为类和同一名字空间中具有相同功能的类,我们可以在名字空间中添加一个类而不会影响该名字空间的其他成员。
  可扩充性   面向对象编程从本质上支持扩充性。如果有一个具有某种功能的类,就可以很快地扩充这个类,创建一个具有扩充的功能的类。
代码重用   由于功能是被封装在类中的,并且类是作为一个独立实体而存在的,提供一个类库就非常简单了。
它比较适合多人合作来开发项目,所以现在很多大中型网站都选择了用OOP来开发。

下面我来来介绍面向对象编程

类与属性和方法

PHP中定义类语法格式:

 代码如下 复制代码
class classname [可选属性]{
public $property [=value];… //用public声明一个公共标识 然后给予一个变量 变量也可以赋值
function functionname ( args ){ //类的方法里的成员函数
代码} …
//类的方法(成员函数)
}

生成对象(类的实例化): $对象名=new classname( );
使用对象的属性

在一个类中,可以访问一个特殊指针$this当在该类中通过一个操作设置或访问该变量时,使用$this->name来引用.

 代码如下 复制代码

class person{
function _ _destruct( )
{ echo "bye bye !“; }
}
$a=new person();


1.final
final:php5新增一个final关键字。如果父类中的方法被声明为final,则子类无法覆盖该方法;如果一个类被声明final,则不能被继承。

 代码如下 复制代码
 
class BaseClass{
     public function test(){
          ehco "test";
     }
 
     final public function moreTest(){
          echo "moretest";
     }
}
 
class ChildClass extends BaseClass{
     public function moreTest(){
          echo "moretest";
     }
}
// 产生 Fatal error: Cannot override final method BaseClass::moretest()

 
2.__toString(建议用PHP5.2或者更高版本)

 代码如下 复制代码
class Person{
     protected $name;
     protected $email;
    
     public function setName($name){
          $this->name = $name;
     }
 
     public function setEmail($email){
          $this->email = $email;
     }
 
     public function __toString(){
          return "$this->name email>";
     }
}
$rasums = new Person;
$rasums->setName('test');
$rasums->setEmail('test@qq.com');
print $rasums;


 
3.接口和抽象类

接口的作用:你想要保证一个类按照特定的名称、可见性和原型实现一个或多个方法。
接口的要求:
     类中全部为抽象方法
     抽象方法钱不用加abstract
     接口抽象方法属性为public
     成员属性必须为常量
例:

 代码如下 复制代码
interface ChildTest{
     public function childTest();
}
class FathTest implements ChildTest1,ChildTest2{
     public function childTest(){
          echo 1;
     }
     …………
}

 
抽象的作用: 其实抽象类和接口类有一部分很像,记得在哪里看见这样一句话,抽象类就把类像的部分抽出来,这句看上去很搞笑,其实它说出了抽象类的真理,抽象类的作用 是,当你发现你的很多类里面用很多方法你不断的在重复写,那你就可以考虑使用抽象类了,你可能会说“我不是可以重写一个类每个公共类我个实例化一个这个公 共类,调用相同的方法就可以了”,这里是可以,实际上抽象类做的工作也就是这个,不过他省去了你实例化的这个步骤,让你就像直接调用本类方法一样方便,而 且你还可以重载这个方法。
抽象的要求:
     类中至少有一个抽象方法
     抽象方法钱必须加abstract
例:

 代码如下 复制代码
abstract class Database{
     abstract public function connect();
     abstract public function query();
     abstract public function fetch();
     abstract public function close();
}

注:抽象方法不能定义为私有方法、不能定义为最终方法,因为它们需要被继承。
 
4.传递对象引用
php4:所有“=”都是创建一个副本
php5:除了对象外,其他“=”进行赋值时,都是创建一个副本;而对象则是引用
 
5.克隆对象
一、
聚合类:
__call方法简介:
当客户端代码用类中未定义的方法时,__call会被调用。
__call()接受两个参数,一个是方法名称,另一个是传递给要调用方法的所有参数(包括数组)
__call()方法返回的任何值都会返回给客户,将好像调用方式真实存在一样
例:

 代码如下 复制代码

class Address{
     protected $city;
     protected $country;

     public function setCity($city){$this->city = $city;}
     public function getCity(){return $this->city;}
     public function setCountry($country){$this->country = $country;}
     public function getCountry(){return $this->country;}
}

class Person{
     protected $name;
     protected $address;
     //浅克隆
     public function __construct(){
          $this->address = new Address;
     }

     public function setName($name){
          $this->name = $name;
     }
     public function getName(){
          return $this->name;
     }

     public function __call($method,$arguments){
          if(method_exists($this->address,$method)){
               return call_user_func_array(array($this->address,$method),$arguments);
          }
     }
     //深克隆
     public function __clone(){
          $this->address = clone $this->address;
     }
}

$test1 = new Person;
$test2 = clone $test1;

$test1->setName('testname1');
$test1->setCity('testcity1');
$test2->setName('testname2');
$test2->setCity('testcity2');

echo $test1->getName().'-'.$test1->getCity()."n";
echo $test2->getName().'-'.$test2->getCity()."n";
//testname1-testcity2
//testname2-testcity2


 
6.重要属性访问(__set __get __isset __unset) __isset __unset5.1之后才有用
作用:拦截对属性的需求,为了提高分离的程度,还要实现__isset()和__unset(),以便当我们用isset来检测属性或者unset()来删除属性,来保证类的行为正确
例:

 代码如下 复制代码

class Person{
     protected $__data = array('email','test');

     public function __get($property){
          if(isset($this->__data[$property])){
               return $this->__data[$property];
          }else{
               return false;
          }
     }

     public function __set($property,$value){
          if(isset($this->__data[$property])){
               return $this->__data[$property] = $value;
          }else{
               return false;
          }
     }
 
     public function __isset($property){
          if(isset($this->__data[$property])){
               return true;
          }else{
               return false;
          }
     }
 
     public function __unset($property){
          if(isset($this->__data[$property])){
               return unset($this->__data[$property]);
          }else{
               return false;
          }
     }
}

$test = new Person;
$test->email= 'test';
var_dump($test->email);

注意:

这两个方法只会捕捉缺少的属性,如果你为你的类定义了一个属性,那么当访问这个属性时php不会调用__get()和__set();
     这两个方法完全破坏了任何属性继承的想法。如果父对象中有个 __get()方法,而你在子类中又实现了自己的__get()方法,那么你的对象不会正确的执行,因为父类的__get()方法永远不会被调用,当然可以用parent::__get()解决

缺点:

速度相对较慢
使用魔术访问器方法就不可能在使用反射类,如phpdocumentor这类的工具将代码自动文档化
不能将其用于静态属性

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

Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months 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).

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

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;

Demystifying C: A Clear and Simple Path for New Programmers Demystifying C: A Clear and Simple Path for New Programmers Oct 11, 2024 pm 10:47 PM

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

See all articles