PHP面向对象总结

PHP面向对象总结

继承

php只支持单继承,一个类最多只能继承一个父类。如果想要实现多类继承可以使用trait关键字来实现。

类的构造函数和与类名相同的方法(以下简称同名方法)优先级的问题

class One {
    public function __construct($a) {
        echo "this is the one class $a";
    }

    public function one() {
        echo "this is the one function";
    }
}

构造方法的优先级要大于同名方法。也就是说当构造方法和同名方法同时存在的时,只会调用构造方法。实例化class one不会调用one方法,只执行构造方法。

子类和父类都存在构造方法时

class One {
    public function __construct($a) {
        echo "this is the one class $a";
    }

    public function one() {
        echo "this is the one function";
    }
}

class Two extends One {
    public function __construct() {
        // parent::__construct("aaaaaaaa\n");
        echo "this is the two class";
    }

    public function two() {
        echo "this is the two function";
    }

    public function abc() {
        echo __FUNCTION__;
    }
}

子类与父类都存在构造方法时候,子类的构造方法会覆盖掉父类的构造方法。即使子类和父类的构造方法所需参数不同,依然会被覆盖。同理,实例化上面的class two 依旧不会触发one方法和two方法,只会触发two的构造方法,打印出 this is the two class。

同名方法

class One {
    public function one() {
        echo "this is the one function";
    }
}

class Two extends One {
    public function two() {
        echo "this is the two function";
    }

    public function abc() {
        echo __FUNCTION__;
    }
}

想象下,当我们把代码编程上面这样,实例化 class two 会发生什么?
实例化 class two 会只会调用 two 方法。同理,当我们注释掉two方法后,在实例化,就只会调用one方法了。
一般情况下将同名方法当作构造方法处理就行了。但是在使用框架的时候,通常会使用到命名空间,此时吧同名方法当作是一个普通方法就好了,就不在具有构造方法的作用了。

parent关键字

class One {
	public function __construct() {
		echo "this is hte one class";
	}
    public function one() {
        echo "this is the one function";
    }
}

class Two extends One {
    public function two() {
    	parent::__construct();
        echo "this is the two function";
    }

    public function abc() {
        echo __FUNCTION__;
    }
}

parent关键字就是用来调用父类的方法。

static和self关键字

static 关键字是调用者的对象(实例化的类的对象)。
self 关键字是当前类的对象(该方法所属的类)。
简而言之,只要你在父类中没有使用 self 关键字,这两个对你来说就是一样的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值