使用命名空间从外部文件调用PHP类。

时间:2015-12-09 21:57:09

标签: php class namespaces

这是我第一次发帖,如果我没有选择,我真的不会这样做(我想做的最后一件事是无缘无故的烦恼)。我已经在这个剧本上工作了几天,用敲击键盘试图弄清楚它为什么不起作用。

文件1:这是一个部分上传类,用于从外部文件中使用。

<?php
namespace Tools\File;
class Upload {

    protected $destination;
    protected $max = 51200;
    protected $messages = array();
    protected $permitted = array('image/gif','image/jpeg', 'image/pjpeg', 'image/png');

    public function __construct($path){
        if (!is_dir($path) || !is_writable($path)) {
            throw new \Exception ("$path must be a valid,writable directory");
        }
        $this->destination = $path;
        }
    public function upload(){
        $upload = current($_FILES);
        if ($this->checkFile($uploaded)){
            $this->moveFile($uploaded);
            }
        }

    protected function checkFile($file){
        return true;
        }
    protected function moveFile ($file) {
        $success = move_uploaded_file($file ['tmp_name'] , $this->destination . $file['name']);
            if ($success){
                $result = $file['name'] . 'was uploaded successfully';
                    $this->messages[] = $result;
            }else{
                $this->messages[] = 'Could not upload' . $file['name'];
                }
        }   
    public function getMessages(){
        return $this->messages;
        }
}

文件2:上传图片的表单

<head>
    <?php use Tools\File\Upload as FileUploader; ?>
</head>
<body>

    <?php
    if(isset($_POST['upload'])){
        // difine the path to the upload folder
        $destination = 'C:/Uploads/';
        // Include upload class
        require_once '../Tools/File/Upload.php';
    // Creates new instance of the upload class as loader
    try{
        $loader = new FileUploader ($destination);
        $loader->getMessages();
    }catch(Exception $e){
        echo $e->getMessages();
        }
    }   
    // Checks and echos result
        if(isset($result)){
            echo '<ul>';
            foreach($result as $message){
                echo "<li>$message</li>";
            }
            echo '</ul>';
        }
        ?>
<form id="uploadImage" enctype="multipart/form-data" action="<?php htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
    <p>
        <label for="image">Upload Image</label>
        <input type="hidden" name="MAX_FILE_SIZE" value="<?= $max; ?>">
        <input type="file" name="image" id="image">

    </p>
    <p>
        <input type="submit" name="upload" value="upload" id="uplaod">
    </p>
</form>
<!-- For checking the Files Super global-->

<pre>
    <?php
    if(isset($_POST['upload'])){ print_r($_FILES);}?>
</pre>

</body>

表单正常。 &#34; move_uploaded_file&#34;&#34; move_uploaded_file&#34;函数在文件2本身内部调用,但它似乎根本不是在调用类。

我已经失去了对代码的重复次数。重新排列并尝试我所知道的所有内容以使其发挥作用。

任何帮助都会非常感激。 提前谢谢你抽出时间。

1 个答案:

答案 0 :(得分:0)

您需要从第二个文件调用upload方法。否则它将实例化Upload类但不会触发任何上传活动。

$(".the_div").css({"transform":"translate(my_width+'px',0px)"});