类:
class ParentClass{
public $a=10;
public function setVal($val){
$this->a = $val;
}
public function getVal(){
return $this->a;
}
}
实例化
$obj = new ParentClass;
echo $obj->a."
";
$obj->setVal(10000);
echo $obj->getVal();
构造函数__construct() 当初始化实例的时候会被触发
class obj{
public function __construct(){
echo "the class".__class__."was initialized !!!";
}
}
new obj;
__destruct() 当实例对象被注销的时候,会自动触发
class obj{
public function __construct(){
echo "the class".__class__."was initialized !!!";
}
public function __destruct(){
echo "Happy Ending !!!";
}
}
$a = new obj;
unset($a);
extends 子类继承父类
class childOne extends ParentClass{
}
new childOne;
当子类存在的变量或则构造函数和父类的相同的时候,会覆盖父类的变量和方法
如果需要保留父类的构造函数同时触发的话,可以使用parent::__construct();
class childOne extends parentClass{
public function __construct(){
parent::__construct();
echo "this is my construct!!!";
}
}
new childOne;
访问标识符
public 变量,方法 所有的类都可以访问
protected 变量,方法 该类内部访问或则子类通过方法向上继承的方式才可以访问,子类不可以直接去访问
private 变量,方法 只允许该类自己内部访问
class ParentClass{
public $a =2000;
public function __construct(){
echo "the class".__class__."was initialized !!!";
}
public function __destruct(){
echo "Happy Ending !!!";
}
protected function getVal(){
return $this->a;
}
}
class childOne extends parentClass{
public function __construct(){
parent::__construct();
echo "this is my construct!!!";
}
}
$ch = new childOne;
echo $ch->getVal();
class ParentClass{
public $a =2000;
public function __construct(){
echo "the class".__class__."was initialized !!!";
}
public function __destruct(){
echo "Happy Ending !!!";
}
protected function getVal(){
return $this->a;
}
}
class childOne extends ParentClass{
public function abcd(){
return $this->getVal();
}
}
$child123 = new childOne;
echo $child123->abcd();
静态变量,静态方法,不需要实例化就可以直接使用的
";
}
}
echo demo::$count."
"; //注意,这里是有$符号的!!!
echo demo::plusOne();
?>
Reference:
https://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762