php 类文件加载 Autoloader

  做习惯了编译语言,转到php 使用 php的面向对象开发时候遇见一个挺别扭的问题。在Php中引入对象 后 在调用过程中还需要将对象所在的php文件

require 到当前php文件

目前代码结构



index.php
<?php

use model\BookModel;

include_once __DIR__.'/autoloader.php';
Autoloader::register();

$book=new BookModel();
$book->id=10;
$book->name="wangk";
echo $book->toString();

?>

 


autoloader.php
<?php

/**
 *
 * 自动载入函数
 */
class Autoloader
{
    /**
     * 向PHP注册在自动载入函数
     */
    public static function register()
    {
        spl_autoload_register(array(new self, 'autoload'));
    }

    /**
     * 根据类名载入所在文件
     */
    public static function autoload($className)
    {

        // DIRECTORY_SEPARATOR:目录分隔符,linux上就是’/’    windows上是’\’
        $filePath = __DIR__ . DIRECTORY_SEPARATOR . $className;
        $filePath = str_replace('\\', DIRECTORY_SEPARATOR, $filePath) . '.php';
        if (file_exists($filePath)) {
            require_once $filePath;
            return;
//                if(method_exists($className, "init")) {
//                    call_user_func(array($className, "init"), $params);
//                }
        } else {
            echo "无法加载" . $filePath;
        }

    }
}

 


bookmodel.php
<?php
/**
 * Created by PhpStorm.
 * User: wangk
 * Date: 2015/7/16
 * Time: 10:14
 */

namespace model;


class BookModel {

     public  $name;
     public  $id;
     public  $age;

    public  function  toString(){

        return 'name:'.$this->name.','.$this->id.",".$this->age;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值