Problem with namespace and include

0

Good morning. I have a webservice made in slimPHP. I have a class that is called control , and it belongs to the controllers namespace, it works normally without problems, but the need arose to import a class for PDF manipulation, so when I give it the error did not find the class requested. Does anyone know what can it be ? Follow the class.

<?php

 namespace controllers {

  include "fpdf/fpdf.php";


   class Control {

    //Atributo para banco de dados
    private $PDO;

    /*
      __construct
      Conectando ao banco de dados
     */

      function __construct() {
        $this->PDO = new \PDO('mysql:host=localhost;dbname=infoged', 'root', 
              '*******'); //Conexão
                  $this->PDO->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); //habilitando erros do PDO
    }

    public function PDF($romaneio) {
       $pdf =  new \fpdf\FPDF("P", "pt", "A4");
       $pdf->AddPage();
    }
  }
 }

Error:

<b>Fatal error</b>:  Class 'fpdf\FPDF' not found in
<b>C:\xampp\htdocs\infoged\services\controllers\Control.php</b> on line
<b>142</b>

Starting the file FPDF

 define('FPDF_VERSION', '1.81');


class FPDF {

    protected $page;               // current page number
    protected $n;                  // current object number
    protected $offsets;            // array of object offsets
    protected $buffer;             // buffer holding in-memory PDF
    protected $pages;      
 .....
 }
    
asked by anonymous 06.06.2017 / 15:15

1 answer

1

The correct form would be:

<?php namespace controllers; // Deve ser a primeira linha do arquivo e não se deve abrir chaves

include "fpdf/fpdf.php";

class Control {

    /*...*/

    public function PDF($romaneio) {
        // Classe está definida no escopo global, por isso se deve passar o \FPDF. Se tentar inicializar sem o \, é como se estivesse no escopo desse namespace, mas ela não está e por isso se deve chamar com \.
        $pdf =  new \FPDF("P", "pt", "A4");
        /*...*/
    }
}
  

Note: I've hidden unnecessary parts of the code to show just where to fix it. Make the change and see if it will work. If you want to call the class FPDF only, instead of \FDPF , you must include fpdf/fpdf.php at the beginning of the namespace controllers; file.

    
06.06.2017 / 15:52