批改状态:合格
老师批语:
今天学习了类的实例化与属性重载的知识
代码:
<?php
//类的声明和实例化
//用class声明一个类
class Demo1{
}
//使用类要先实例化
$demo1=new Demo1();
//给对像添加一些属性和方法
$demo1->name='tom';
$demo1->sex='男';
$demo1->hello=function (){
return '我是一个自定义的类方法';
};
//使用对象访问符:-> 来访问对象中的成员(属性和方法)
echo $demo1->name,':',$demo1->sex,'<br>';
//错误的调用方式,
//echo $demo1->hello();
echo call_user_func($demo1->hello);点击 "运行实例" 按钮查看在线实例
<?php
//类的声明和实例化
//用class声明一个类
class Demo1{
}
//使用类要先实例化
$demo1=new Demo1();
//给对像添加一些属性和方法
$demo1->name='tom';
$demo1->sex='男';
$demo1->hello=function (){
return '我是一个自定义的类方法';
};
//使用对象访问符:-> 来访问对象中的成员(属性和方法)
echo $demo1->name,':',$demo1->sex,'<br>';
//错误的调用方式,
//echo $demo1->hello();
echo call_user_func($demo1->hello);点击 "运行实例" 按钮查看在线实例
<?php
class Demo3{
//父类属性
public $name;
protected $age;
private $salary;
const APP_NAME='学生管理系统';
public function __construct($name,$age)
{
$this->name=$name;
$this->age=$age;
}
public function __get($name)
{
if(isset($this->$name)){
return $this->$name;
}
return '非法属性';
}
}
class Demo3_1 extends Demo3{
//子类自有属性
private $sex;
//子类将父类同名方法进行重写,根据传入参数不同,实现不同的功能,这就是多态性
public function __construct($name, $age,$sex='mela')
{
parent::__construct($name, $age);
$this->sex=$sex;
}
public function __get($name)
{
if(isset($this->$name)){
return $this->$name;
}
return '非法属性';
}
}
//当前类Demo3_1中即使没有任何成员,一样可以访问父类成员
$demo3_1=new Demo3_1('tom',80);
//访问父类中的属性
echo $demo3_1->name,'<br>';
echo $demo3_1->age,'<br>';
echo $demo3_1->salary,'<br>';点击 "运行实例" 按钮查看在线实例
<?php
class Demo4{
public static $pdo=null;
protected static $db=[
'type'=>'mysql',
'host'=>'127.0.0.1',
'dbname'=>'php',
'user'=>'root',
'pass'=>'root',
];
public static function connect(){
$dns=self::$db['type'].':host='.self::$db['host'].';dbname='.self::$db['dbname'];
self::$pdo=new PDO($dns,self::$db['user'],self::$db['pass']);
}
public static function select($table,$fields='*', $num=5)
{
$stmt = self::$pdo->prepare("SELECT {$fields} FROM {$table} LIMIT {$num}");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
Demo4::connect();
$result = Demo4::select('staff','name,age,salary',8);
echo '<pre>',var_export($result);点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号