php面向对象精要(3)

时间:2022-02-19 03:38:48

1,final关键字定义的方法,不能被重写

由于final修饰了show方法,子类中重写show方法会报错

<?php

    class MyClass {
final function show(){
echo "hello world" . PHP_EOL;
}
} class MyTest extends MyClass {
function show(){
echo __CLASS__ . PHP_EOL;
}
} ?>

2,final定义的class不能被继承

<?php

    final class MyClass {
function show(){
echo "hello world" . PHP_EOL;
}
} class MyTest extends MyClass {
} ?>

3,__toString方法

如果定义了__toString方法,打印一个对象时,将调用__toString

class Person {
private $name;
function __construct( $name ){
$this->name = $name;
}
function __toString(){
return $this->name;
}
} $p = new Person( "ghostwu" );
var_dump( $p );
echo PHP_EOL;
print $p . PHP_EOL;

4, 异常处理( try, catch, throw )

>异常处理类都应该继承自系统自带的Exception

>异常抛出时( throw 异常对象 ),会一个个查找catch后面的异常处理,如果匹配到,就执行,后面的catch就算能匹配,也不会执行

Exception类摘要:

Exception {
/* 属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 方法 */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public string getMessage ( void )
final public Throwable getPrevious ( void )
final public int getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )
}
 class NullHandleException extends Exception {
function __construct( $message ){
parent::__construct( $message );
}
} function printObj( $obj ){
if( $obj == NULL ) {
throw new NullHandleException( "printObj接收到一个null对象" );
}
print $obj . PHP_EOL;
} class Person {
private $name;
function __construct( $name ) {
$this->name = $name;
}
function __toString() {
return $this->name;
}
} try {
printObj( new Person( "ghostwu" ) );
printObj( null );
printObj( new Person( "zhangsan" ) );
}catch( NullHandleException $exception ){
print $exception->getMessage() . PHP_EOL;
print "in file:" . $exception->getFile() . PHP_EOL;
print "in line:" . $exception->getLine() . PHP_EOL;
}catch( Exception $exception ){
echo "这个异常分支不会被执行" . PHP_EOL;
print $exception->getMessage() . PHP_EOL;
} echo "try...catch处理完毕" . PHP_EOL;

输出结果:

ghostwu@ubuntu:~/php_study/php5/03$ php -f exception_usage.php
ghostwu
printObj接收到一个null对象
in file:/home/ghostwu/php_study/php5/03/exception_usage.php
in line:10
try...catch处理完毕

没有输出"zhangsan", 因为printObj( null );抛出了异常,因此"zhangsan"被忽略

5,__autoload自动加载文件

在项目开发中,经常需要在一个文件中包含多个通用的库文件,这个时候会产生一大堆的require或者include,而使用__autoload函数可以简化函数的加载过程

1,MyClass.php

 class MyClass {
function printHelloWorld(){
echo "Hello World" . PHP_EOL;
}
}

2,common.inc

function __autoload( $className ) {
require_once( "./{$className}.php" );
}

3,main.php

require_once "common.inc";

    $obj = new MyClass();
$obj->printHelloWorld();