批改状态:合格
老师批语:
作业标题:0812 oop编程-2
作业内容:oop基础:请举例实例演绎以下难点 1. 类(对象抽象化的结果)与对象 (类实例化结果) 2. 构造方法 3. 对象成员之间的内部访问 $this 4. private仅限本类中使用 protected本类中,子类中使用 5. 类的自动加载 spl_autoload_register 6. 静态成员的访问 类的引用self:: 7. 类的继承 扩展 父类方法(魔术方法,普通方法)的重写 parent:: 调用父类成员

构造方法
<?phpclass Student{public $username;public $hight;private $age;protected $gender;// __construct()魔术方法 构造函数 构造器 类实例化一次就被自动调用一次 __get __set __call __callStaticpublic function __construct($username, $hight, $age,$gender){// 1. 初始化类成员 让类/实例化的状态稳定下来// 2. 给对象属性进行初始化赋值// 3.可以给私有成员,受保护的成员初始化赋值$this->username = $username;$this->hight = $hight;$this->age = $age;$this->gender = $gender;}public function run(){return "姓名:$this->username,身高:$this->hight,年龄:$this->age,$this->gender";}}$test=new Student("张三","170",25,"男");echo $test->run();?>





类的自动加载 spl_autoload_register
自动加载代码
<?phpspl_autoload_register(function($className){// 先查看要加载的类printf('类名:%s<br>',$className);// 将类命名空间与类所在的路径进行一一映射// linux / window \// 解决在linux系统中命名空间失效的问题$file = __DIR__.'\\controller\\'.str_replace('\\',DIRECTORY_SEPARATOR,$className).'.php';// echo $file;if(!(is_file($file) && file_exists($file))){throw new \Exception('文件名不合法或者不存在');}require $file;);



Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号