您的位置:首页 > 编程语言 > PHP开发

php面向对象三,继承父类extends

2016-05-01 00:00 645 查看
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>继承</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
class Human{
private $height=170;
public function show()
{
echo $this->height;
}
}
/**
* 继承Human父类
*/
class Student extends Human
{
private $height=180;

public function show()
{   //调用父类的方法
parent::show();
echo $this->height;
}
}
$st=new Student();
$st->show();
?>
</body>
</html>

构造方法也可以被继承
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>构造方法的继承</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
/**
*
*/
class Human
{

function __construct()
{
echo "helloworld";
}
}
/**
* 构造函数也是可以被继承的
*/
class Student extends Human
{

function __construct()
{
echo "hellonihao ";
}
}
$s=new Student();
?>
</body>
</html>

private 只能在内部类中访问,protected可以被子类内部访问。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>构造方法的继承</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
// private 私有,只能被内部调用。
//protected可以被继承的子类调用
/**public private  protected
内部类   Y      Y        Y
子类     Y      N        Y
外部类   Y       N       N
*
*/
class Human
{
private $a="1";
protected $b="2";
public $c="3";
public function talk()
{
echo $this->a,',',$this->b,',',$this->c;
}
}
class student extends Human{
public function say()
{
// echo $this->a,'<br/>';private只能在本类内调用
echo $this->b,',',$this->c;
}
}
$s=new student();
$s->say();
?>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: