PHP Object-oriented (vi)

Source: Internet
Author: User
Tags autoload

First, exception handling
Exception (Exception): is a program in the execution of an exception or an event, it interrupts the execution of the normal instruction, jump to other program modules continue to execute, seriously causing the loss of data or program crashes.

Exception handling: Used to change the normal process of a script when a specified error occurs. is a new and important feature in the PHP5. Exception handling is an extensible and maintainable mechanism for error handling, and provides a new object-oriented error handling method.

When an exception is triggered, it usually occurs:

1. Current code status is saved
2. Code execution is switched to pre-defined exception handler function
3. Depending on the situation, the processor may restart execution of the code from the saved code State, terminate the script execution, or resume execution of the script from another location in the code

Exception handling Format:
try{
Use the try to include code that could potentially cause an exception to occur.
Once an exception is made, try to catch the exception and give it a catch handle.
Throw Exception Statement: Throw exception object.
}catch (Exception object parameter) {
Do the exception handling here.
}[catch (... ){
.. .. ..
}]
  

  Rules for Exceptions:
The code that requires exception handling should be placed inside a try code block to catch a potential exception.
Each try or throw code block must have at least one corresponding catch code block.
You can use multiple catch blocks to catch different kinds of exceptions.
You can throw (re-thrown) exceptions again in a catch code block within a try code block.
In short: If an exception is thrown, it must be captured.

1<?PHP2     //simulate an exception throw and handle3         Try {4             $error= ' Always throw this error ';5             Throw New Exception($error); 6             //creates an exception object, thrown by a throw statement7             Echo' Never executed '; 8             //from here, the code inside the try code block will no longer be executed9}Catch(Exception $e) {Ten             Echo' Caught exception: '.$e->getmessage (). " <br> ";  One             //output-caught exception message A         } -         Echo' Hello world ';//program does not crash continue down execution -?>

Ii. Custom Exception Handling classes

1. System exception Handling: The built-in exception handling class provided in PHP exception is the base class for all exception classes, and all system-built exception-handling classes or custom exception-handling classes must inherit from this class.

The structure of the built-in exception handling class exception:

1<?PHP2     classException{3protected$message= ' Unknown exception ';//Exception Information4         protected$code= 0;//user-defined exception codes5         protected$file;//the file name of the exception that occurred6         protected$line;//the line number of the code where the exception occurred7           8 //Construction method9         function__construct ($message=NULL,$code= 0); Ten  One         FinalfunctionGetMessage ();//Return exception Information A         FinalfunctionGetCode ();//return Exception Code -         FinalfunctionGetFile ();//returns the file name of the exception that occurred -         FinalfunctionGetLine ();//returns the line number of the code where the exception occurred the         FinalfunctionGettrace ();//backtrace () array -         FinalfunctionGettraceasstring ();//Gettrace () information that has been rasterized into a string -              -         /*methods that can be overloaded*/    +         function__tostring ();//A string that can be output -     } +?>

2. Custom Exception Handling classes

1<?PHP2     /*a custom exception-handling class, but must be a subclass of the exception-handling class within the extension*/3     classMyExceptionextends Exception{4         //Redefine the constructor so that the first parameter message becomes a property that must be specified5          Public function__construct ($message,$code=0){6             //You can define some of your own code here7 //It is recommended to call Parent::construct () at the same time to check that all variables have been assigned8Parent::__construct ($message,$code);9         }    Ten          Public function__tostring () { One           //overriding the parent class method, customizing the style of the string output A           return __class__.":[".$this->code. "]:".$this->message. " <br> "; -         } -          Public functioncustomfunction () { the              //customize a processing method for this exception -              Echo"Handling of this type of exception that occurs by a custom method <br>"; -         } -     } +?>
1<?PHP2    Try{//catch an exception with a custom exception class and handle the exception3         $error= ' Allow this error to be thrown '; 4         Throw NewMyException ($error); 5              //creates a custom exception class object that is thrown by the throw statement6         Echo' Never executed '; 7             //from here, the code inside the try code block will no longer be executed8}Catch(myexception$e) {//capturing a custom exception object9         Echo' Catch exception: '.$e;//output-caught exception messageTen         $e->customfunction ();//handling exceptions through a method in a custom exception object One     } A     Echo' Hello ';//program does not crash continue down execution -?>

Iii. Capturing multiple exceptions
After the try code, you must give at least one catch code block, or you can associate multiple catch blocks with a try block of code. You can use multiple catches to catch exceptions from different classes. Note the order. exception must be in the last catch, or else the catch will be meaningless.

Iv. related functions of classes and objects in PHP
============================
Classes/object function
============================
Reference Manual--extension functions related to objects and classes
1. class_alias-Create an alias for the class
Format: bool Class_alias ([String $original [, String $alias])
Example:
class Foo {}
Class_alias (' foo ', ' Bar ');

$a = new Foo;
$b = new Bar;
The objects is the same
Var_dump ($a = = $b, $a = = = $b); BOOL (TRUE)
Var_dump ($a instanceof $b);//bool (false)

The classes is the same
Var_dump ($a instanceof foo);//bool (True)
Var_dump ($a instanceof bar);//bool (True)

Var_dump ($b instanceof foo);//bool (True)
Var_dump ($b instanceof Bar);//bool (True)


* *. class_exists-checking whether a class is defined
Format: bool Class_exists (String $class _name [, BOOL $autoload])
-If the class referred to by class_name is already defined, this function returns TRUE, otherwise FALSE is returned.

The default will attempt to call __autoload, if you do not want class_exists () to call __autoload,
You can set the AutoLoad parameter to FALSE.


3. Get_called_class-the "Late Static Binding" class name
(PHP 5 >= 5.3.0) Gets the class name of the caller


. get_class_methods-returns an array of the method names of the class
Format: Array get_class_methods (mixed $class _name)
Returns an array of the method names that are defined in the class specified by Class_name. If an error occurs, NULL is returned.

Starting with PHP 4.0.6, you can specify the object itself instead of the class_name


5. get_class_vars-returns an array of the default public properties of the class
Format: Array get_class_vars (string $class _name)
Returns an associative array of the default public properties of the class, with elements of this array in the form of varname = = value.


*6. get_class-returns the class name of the object
Format: String Get_class ([object $obj])
Returns the name of the class to which the object instance obj belongs. Returns FALSE if obj is not an object.


7. get_declared_classes-returns an array consisting of the names of the defined classes
Format: Array get_declared_classes (void)
Returns an array of the names of the defined classes in the current script.


8. get_declared_interfaces-returns an array containing all the declared interfaces
Format: Array get_declared_interfaces (void)
This function returns an array whose contents are the names of all declared interfaces in the current script.


9. get_object_vars-returns an associative array consisting of object properties
Format: Array get_object_vars (object $obj)
Returns an associative array of properties that are defined in the object specified by obj.


get_parent_class-returns the parent class name of an object or class
Format: String Get_parent_class ([mixed $obj])
If obj is an object, the parent class name of the class to which the object instance obj belongs is returned.


interface_exists-Check if the interface has been defined
Format: bool Interface_exists (String $interface _name [, BOOL $autoload])
This function returns TRUE if the interface given by interface_name is defined, otherwise FALSE.


*12. is_a-returns TRUE if the object belongs to the class or if the class is the parent class of this object
We can use the operator: instanceof instead of the is_a operation above

PHP Object-oriented (vi)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.