Home > Mobile >  require a class from another class - php
require a class from another class - php

Time:05-05

I'm learning PHP. And I have a problem that I can't understand. This my situation:

I have a directory called Lib. This is the structure of my directory:

enter image description here

In the directory database I wrote a class QueryBuilder.

<?php

//require '../Task';

class QueryBuilder{

    public function selectAll($table,$pdo){

        $statement = $pdo->prepare("Select * from {$table}");

        $statement->execute();

        return $statement->fetchAll(PDO::FETCH_CLASS,'Task');

    }

}

?>

In the class I use an external class Task that I wrote before and that I use in the statement. return.

return $statement->fetchAll(PDO::FETCH_CLASS,'Task');

This is the Task class:

<?php

    class Task{
        
        protected $description;
        protected $completed=false;
    
        public function __contruct($description){
    
            $this->description = $description;
    
        }
    
    
        public function getDescription(){
    
            return $this->description;
    
        }
    
    
        public function getCompleted(){
    
            return $this->completed;
        }
    
    }
    
    
    ?>

So I thought that If I wanted to use the Task class I had to import the file. So at the beginnig of the my class QueyBuilder I wrote the require statement.

require '../Task';

The problem is that when I run my class I get this error:

Warning: require(../Task): failed to open stream: No such file or directory in C:\Users\Administrator\OneDrive - Sogei\Desktop\php-learning\php-course\Lib\database\QueryBuilder.php on line 3

Fatal error: require(): Failed opening required '../Task' (include_path='C:\xampp\php\PEAR') in C:\Users\Administrator\OneDrive - Sogei\Desktop\php-learning\php-course\Lib\database\QueryBuilder.php on line 3

Without the require statement instead the class works.

How is it possible? Is not necessary import the Task class?

CodePudding user response:

It is more usefull to use dirname. For exemple in your case :

require dirname(__FILE__, 2) . '/Task.php';

It will search the file in second level of your arbo of your class.

In an other end, you can use an autoload called by your frontend script.

And for the error, 'Task' doesn't exist. It's 'Task.php' witch exists.

CodePudding user response:

You might want to try require __DIR__ . /../Task.php you're also missing the .php File extension. If it's not working, try to use it in the constructor. Also notice, that you should work with an autoloader and namespaces, it's pretty easy to configure.

  • Related