php的面向对象

php的面向对象:

1:类,对象,字段,方法:

<?php
	class Computer{              //类的声明
		private $_a;             //字段的声明
                function __construct(){} //构造方法,只要实例化类就会被执行
		public function a(){     //方法的声明
			echo "string";
		}
	}
	$_computer = new Computer();  //new 出一个对象
?>

2:字段的作用域:

public:公共的,类外可以访问;

private:私有的类内可以访问;

protected:受保护的,类内和子类可以访问。

3:私有字段的访问方法:

     3.1:公共方法访问私有字段,访问私有方法:

<?php
	class Computer{              //类的声明
		private $_a = 1;        //字段的声明
		public function a(){     //通过公共方法访问私有变量
			return $this->_ab;
		}

	}

	$_computer = new Computer();  //new 出一个对象
	echo $_computer->a();
?>

     3.2:属性操作,私有字段的赋值与取值:拦截器;

<?php
	class Computer{              //类的声明
		private $_a = 1;        //字段的声明
		// 赋值
		public function __set($_key,$_value){
			$this->$_key = $_value;
		}
		// 取值
		public function __get($_key,$_value){
			return $this->$_key;
		}
	}
	$_computer = new Computer();  //new 出一个对象
	$_computer->a = 2;     		  // 赋值
	echo $_computer->a;           // 取值
?>

4:常量,静态类;

<?php
	class Computer{             
		const A = 1;         //常量   
		private static $_a = 2;  //静态字段
		public static function get(){  //公共静态方法访问私有静态变量
			return self::$_a;
		} 
	}
	echo Computer::A;       //1
	echo Computer::get();    //2
?>

5:OOP继承:

<?php
	class Computer{
		protected $a = 1;
		protected function run(){
			return $this->a;
		} 
		function __construct(){}  //构造方法
	}
	class NoteComputer extends Computer{
		public function get(){
			echo $this->:run();  //调用从父类中继承的方法
			echo parent::run();  //调用父类的方法如果父类中的方法被覆盖了的话
		}
		function __construct(){}  //重写构造方法
	}
	$_note = new NoteComputer();
	echo $_note->get();
?>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值