Home Backend Development PHP Tutorial php5 学习记要(1)

php5 学习记要(1)

Jun 13, 2016 am 10:49 AM
class function obj print

php5 学习记录(1)

一、php5主要的新特性

1.public /private/protected访问修饰符,针对对象中的方法和属性。

可以使用通用的面向对象访问修饰符来控制方法和属性的访问级别:

class MyClass {

    private $id = 18;    public function getId() {        return $this->id;    }}
Copy after login
?

2.统一的构造函数名称__construct().

为避免构造函数的名字和类的名字相同,现在用__construct()来声明,从而让你更加容易在类的分层中转移类:

?

class MyClass {    function __construct() {        print 'Inside constructor';    }}
Copy after login

?

? 3.通过__destructor()定义对象的析构方法。

允许定义一个析构函数来注销一个对象:

?

class MyClass {    function __destruct() {        print ' Destroying object';    }}
Copy after login

?

? 4.接口。

一个使用接口的类可以加载不止一个相关的接口。一个类只能继承自另一个类,但是可以实现任意多个接口:

?

interface Display {    function display();}class Circle implements Display {    function dispaly() {        print ' Dispalying circle \n';    }}
Copy after login

?

? 5.instanceof操作符。

instanceof用来检测一个给定的对象是否属于(继承于)某个类(class)、某个类的子类、某个接口(interface)。如果是则返回true。

?

if ($obj instanceof Circle) {    print '$obj is a Circle';}
Copy after login
?

?

?

6.Final 标记方法。

Final关键字允许你用来标识方法,使其不能被子类重载。

?

class MyClass {    final function getBaseClassName() {        return __CLASS__;    }}
Copy after login
?

?

7.Final标记类。

声明一个类为final类型后,它将不能被继承。下面的例子将报错。

?

final class FinalClass {}class BogusClass extends FinalClass {}
Copy after login

?

?

8.强制复制对象

为了克隆一个对象,你必须使用clone关键字。你可以再类中声明一个__clone()方法,它将在克隆过程中被调用(调用在属性和方法从原对象复制过来以后进行):

?

class MyClas {    function __clone() {        print 'Object is being cloned';    }}$obj = new MyClass();$obj_copy = clone $obj;
Copy after login
?

?

9.类中的常量。

类定义中现在包含常量,而且可以用类来引用:

?

class MyClass {    const SUCCESS = "Success";    const FAILURE = "Failure";}print MyClass::SUCCESS;
Copy after login

?

? 10.静态方法。

你现在可以定义静态方法,不用实例化就能使用他们。静态方法不能使用$this变量,因为它们并没有绑定到任何具体的对象:

class MyClass {

    static function helloWorld() {        print 'Hello world';    }}MyClass::helloWorld();
Copy after login

?

11.静态成员。

类的定义现在包含静态成员(属性),可以通过类自身来访问。通常用的最多的是单件(Singleton)模式:

?

class Singleton {    static private $instance = NULL;    private function __construct() {    }    static public function getInstance() {        if (sell::$instance == NULL) {            self::$instance = new Singleton();        }        return self::$instance;    }}
Copy after login

?

?

12.抽象类。

把类声明为抽象类可以防止它被实例化。但是你可以继承一个抽象类:

?

abstract class MyBaseClass {    function dispaly() {        print 'Default dispaly routine being called';    }}
Copy after login
?

?

13.抽象方法。

把方法声明为抽象的,以便在继承的子类中再去定义。包含抽象方法的类本身必须是一个抽象类:

?

abstact class MyBaseClass {    abstract function dispaly();}
Copy after login

?

? 14.对象类型提示。

函数声明中可以对参数进行对象类型提示。如果函数调用的时候没有传递正确的对象类型,系统报错:

?

function expectsMyClass(MyClass $obj) {}
Copy after login

?

? 15.支持连续引用方法返回的对象。

在PHP4中,你不能直接引用方法返回的对象。你必须先赋值到一个中间变量,然后再使用该变量来引用。

php 4:

?

$dummy = $obj->method();$dummy->method2();
Copy after login

?

? php 5:

?

$obj->method()->method2();
Copy after login

?

?

16.迭代。

php5允许php类和php继承类实现iterator接口。在实现迭代接口后,你可以用foreach()语言结构遍历一个类的实例:

?

$obj = new MyIteratorImplementaion();foreach ($obj as $value) {    print $value;}
Copy after login

?

?

17.__autoload()方法。

__autoload()函数在你需要使用一个未定义的类的时候自动调用。通过调用这个函数,脚本的引擎在php抛出类未定义的错误之前提供最后一次加载类的机会:

?

function __autoload($class_name) {    include_once($class_name . "php");}$obj = new MyClass();$obj2 = new MyClass2();
Copy after login
?

18.异常处理。

php5增加了著名的try/throw/catch架构的异常处理范例。使用时,你只能抛出从Exception类继承的对象:

class SQLException extends Exception {

    public $problem;    function __construct($problem) {        $this->problem = $problem;    }}try{ ...     throw new SQLException("Couldn't connect to database"); ...} catch (SQLException $e) {     print "SQLException";} catch (Exception $e) {    print 'Other Exception';}
Copy after login

?

19.foreach 函数支持引用。

在php 4中,你不能遍历一个数组的同时更改它的值。但是php 5可以通过给foreach()循环的参数加速&(引用)符号,让你在遍历数组的循环中更改数组的值:

?

foreach ($array as &$value) {    if ($value === "NULL") {        $VALUE = NULL    }}
Copy after login

?

? 20.给引用参数设置默认值。

在php 4中,你只能给传递值的参数设置默认值。php 5 现在可以让你给传递引用的参数设置默认值:

?

function my_func(&$arg = null) {    if ($arg === NULL) {        print '$arg is empty';    }}my_func();
Copy after login
?

?

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How to use classes and methods in Python How to use classes and methods in Python Apr 21, 2023 pm 02:28 PM

Concepts and instances of classes and methods Class (Class): used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes. Method: Function defined in the class. Class construction method __init__(): The class has a special method (construction method) named init(), which is automatically called when the class is instantiated. Instance variables: In the declaration of a class, attributes are represented by variables. Such variables are called instance variables. An instance variable is a variable modified with self. Instantiation: Create an instance of a class, a specific object of the class. Inheritance: that is, a derived class (derivedclass) inherits the base class (baseclass)

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

What does class mean in python? What does class mean in python? May 21, 2019 pm 05:10 PM

Class is a keyword in Python, used to define a class. The method of defining a class: add a space after class and then add the class name; class name rules: capitalize the first letter. If there are multiple words, use camel case naming, such as [class Dog()].

Replace the class name of an element using jQuery Replace the class name of an element using jQuery Feb 24, 2024 pm 11:03 PM

jQuery is a classic JavaScript library that is widely used in web development. It simplifies operations such as handling events, manipulating DOM elements, and performing animations on web pages. When using jQuery, you often encounter situations where you need to replace the class name of an element. This article will introduce some practical methods and specific code examples. 1. Use the removeClass() and addClass() methods jQuery provides the removeClass() method for deletion

Detailed explanation of PHP Class usage: Make your code clearer and easier to read Detailed explanation of PHP Class usage: Make your code clearer and easier to read Mar 10, 2024 pm 12:03 PM

When writing PHP code, using classes is a very common practice. By using classes, we can encapsulate related functions and data in a single unit, making the code clearer, easier to read, and easier to maintain. This article will introduce the usage of PHPClass in detail and provide specific code examples to help readers better understand how to apply classes to optimize code in actual projects. 1. Create and use classes In PHP, you can use the keyword class to define a class and define properties and methods in the class.

Vue error: Unable to use v-bind to bind class and style correctly, how to solve it? Vue error: Unable to use v-bind to bind class and style correctly, how to solve it? Aug 26, 2023 pm 10:58 PM

Vue error: Unable to use v-bind to bind class and style correctly, how to solve it? In Vue development, we often use the v-bind instruction to dynamically bind class and style, but sometimes we may encounter some problems, such as being unable to correctly use v-bind to bind class and style. In this article, I will explain the cause of this problem and provide you with a solution. First, let’s understand the v-bind directive. v-bind is used to bind V

How to determine whether an element has a class in jquery How to determine whether an element has a class in jquery Mar 21, 2023 am 10:47 AM

How jquery determines whether an element has a class: 1. Determine whether an element has a certain class through the "hasClass('classname')" method; 2. Determine whether an element has a certain class through the "is('.classname')" method.

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

See all articles