【OOP】day03
作者: thtomatic 分类: php笔记
评论: [ 0 ] 条 浏览: [ 819 ] 次
面向对象
面向对象的三大特征
封装 、继承、多态
封装:
一、概念
封装就是用访问修饰符来修饰成员方法和成员属性。从而达到对成员方法和成员属性的隐藏和访问控制。
二、访问修饰符
public:被public修饰的成员方法和成员属性,在类里和类外都可以被访问。
protected:
private:私有化的成员属性在类外不可以访问。
私有化的成员属性在类里可以被访问。
私有化的成员方法在类外不可以被访问。
私有化的成员方法在类里可以被访问。
魔术方法
1、方法名称固定。一般以__(两个下划线)作为魔术方法的开始。
2、所有的魔术方法都不用明确调用。都有自己的特定触发机制。
3、所有的魔术方法都有特殊的用途。
4、对于不同的魔术方法,有不同的语法要求。
__get()
当在类外访问一个私有化成员属性时,魔术方法__get会被自动访问。
必须有一个参数。这个参数就是在类外访问的私有化成员属性。
__set()
在类外给私有化成员属性赋值时。魔术方法__set会被自动调用。
必须有两个参数。
继承
一、概念
用一个已经定义好的类,继承先前定义的类。在这个已经定义好的类中可以应用先前定义好的类中的成员方法和成员属性。 并且在这个已经定义好的类中可以有自己的成员方法和成员属性。从而达到一种类的层级关系。
先前定义好的类:父类
已经定义好的类:子类
PHP中的继承是单继承的。
二、语法
class 子类名称 extends 父类名称{
}
应用继承的原因:
1、省略代码
2、父类是为了声明规则。
验证码封装的类:
021 | function __construct( $width , $height , $length ){ |
022 | $this ->width = $width ; |
023 | $this ->height = $height ; |
024 | $this ->length = $length ; |
042 | private function bg(){ |
043 | $this ->img = imagecreatetruecolor( $this ->width, $this ->height); |
044 | $bg_color = imagecolorallocate( $this ->img,rand(200,255),rand(200,255),rand(200,255)); |
045 | imagefill( $this ->img,0,0, $bg_color ); |
048 | private function disturb(){ |
049 | for ( $i =0; $i <100; $i ++){ |
051 | $color = imagecolorallocate( $this ->img,rand(100,200),rand(100,200),rand(100,200)); |
052 | imagesetpixel( $this ->img,rand(1, $this ->width-1),rand(1, $this ->height-1), $color ); |
056 | for ( $i =0; $i <10; $i ++){ |
058 | $color = imagecolorallocate( $this ->img,rand(100,200),rand(100,200),rand(100,200)); |
059 | imageline( $this ->img, |
060 | rand(1, $this ->width-1),rand(1, $this ->height-1), |
061 | rand(1, $this ->width-1),rand(1, $this ->height-1), |
067 | private function getCode(){ |
068 | $cods = "1234567890abcdefghijklmnopqrstuvwxyz" ; |
069 | for ( $i =0; $i < $this ->length; $i ++){ |
071 | $this ->words.= substr ( $cods , |
072 | rand(0, strlen ( $cods )-1), |
075 | $_SESSION [ 'vcode' ]= $this ->words; |
078 | private function printWord(){ |
079 | for ( $i =0; $i < $this ->length; $i ++){ |
080 | $color = imagecolorallocate( $this ->img,rand(0,100),rand(0,100),rand(0,100)); |
082 | $x = ( $this ->width/ $this ->length)* $i +5; |
084 | $code = substr ( $this ->words, $i ,1); |
085 | imagestring( $this ->img, $font , $x , $y , $code , $color ); |
091 | private function outImg(){ |
092 | header( "Content-Type:image/png" ); |
093 | imagepng( $this ->img); |
097 | function __destruct(){ |
098 | imagedestroy( $this ->img); |
101 | $code = new Code(80,30,4); |
发表评论: