欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php面向对象精要(2)

程序员文章站 2022-09-26 17:03:20
1,self与parent关键字 >self指向当前的类,常用来访问静态成员,方法和常量 >parent指向父类,常用来调用父类的构造函数和方法和成员,也可以用来访问常量 2,instanceof >判断一个对象是否是某个类的实例 >判断一个对象是否实现了某个接口 3,abstract类和方法 >抽 ......

1,self与parent关键字

>self指向当前的类,常用来访问静态成员,方法和常量

>parent指向父类,常用来调用父类的构造函数和方法和成员,也可以用来访问常量

 1 <?php
 2 class Ancestor {
 3     const NAME = "Ancestor";
 4     function __construct(){
 5         echo self::NAME . PHP_EOL;
 6     }
 7 }
 8     
 9 class Child extends Ancestor {
10     const NAME = "Child";
11     function __construct () {
12         parent::__construct();
13         echo self::NAME . PHP_EOL;
14     }
15 }
16 
17 $obj = new Child();
18 ?>

2,instanceof

>判断一个对象是否是某个类的实例

>判断一个对象是否实现了某个接口

 1 <?php
 2 
 3     class Rectangle {
 4         public $name = __CLASS__;
 5     }
 6 
 7     class Square extends Rectangle {
 8         public $name = __CLASS__;
 9     }
10 
11     class Circle {
12         public $name = __CLASS__;
13     }
14 
15     function checkIfRectangle( $shape ) {
16         if( $shape instanceof Rectangle ) {
17             echo $shape->name . PHP_EOL;
18         }
19     }
20 
21     checkIfRectangle( new Square() );
22     checkIfRectangle( new Rectangle() );
23     checkIfRectangle( new Circle() );
24 ?>

 3,abstract类和方法

>抽象类不能被实例化

>抽象方法必须被重写

>只要有一个方法声明为abstract,这个类必须声明为abstract的,当然可以直接把这个类声明为抽象类

<?php
abstract class Shape {
    protected $x;
    protected $y;
    function setCenter( $x, $y ) {
        $this->x = $x;
        $this->y = $y;
    }
    
    abstract function draw();
    abstract function show();
}

class Square extends Shape {
    function draw() {
    }
    function show(){
    }
}

class Circle extends Shape {
    function draw(){
    }
    function show(){
    }
}

?>

4,interface

>接口类似c++的多重继承,  class A implements B, C ... {}

>实现了该接口的类,都将与该接口形成是一关系 (instanceof )

>多重接口之前不能互相冲突( 指的是定义相同的常量和方法 )

interface Loggable {
    function logString();
}

class Person implements Loggable {
    private $name;
    private $age;
    function __construct( $name, $age ){
        $this->name = $name;
        $this->age = $age;
    }
    function logString() {
        return "Class Person: name = {$this->name}, age = {$this->age}" . PHP_EOL;
    }
}

class Product implements Loggable {
    private $name;
    private $price;
    function __construct( $name, $price ){
        $this->name = $name;
        $this->price = $price;
    }

    function logString() {
        return "Class Product: name = {$this->name}, price = {$this->price}" . PHP_EOL;
    }
}

function MyLog( $obj ) {
    if ( $obj instanceof Loggable ) {
        echo $obj->logString();
    }else {
        echo $obj . "没有实现Loggable接口";
    }
}

$p = new Person( "ghostwu", 20 );
echo $p->logString();
$goods = new Product( "book", 19.99 );
echo $goods->logString();
MyLog( $p );
MyLog( $goods );