Problem when including class in a PHP

2

I'm working on PHP and to test my program I'm trying to make the simple lines of code that you see in the image

include("model\product.php");

      $product = new Product();
      $product->setName("Remera");
      $product->setDescription("una remera nike");
      $product->setPrice(400);
      $product->setSex("M");
      $product->setProductcode("AAA1");


      echo $product->toString();

But at the moment of doing the new Product() it gives me an error that does not know the class. Code of the Product class in PHP:

    namespace model;

      class Product
      {

        private $name;
        private $description;
        private $price;
        private $productcode;
        private $sex;
        private $images = array();

        public function __construct()
        {

        }

    public function toString()
    {
      return $this->name." ".$this->price;
    }

// Getters Setters
    
asked by Franco Rolando 06.12.2018 в 02:29
source

1 answer

3

Your problem should be solved by doing the following in the file prueba.php :

<?php

include("model\product.php");

use model\Product;

That is, you included the Product class within the namespace model , so when you try to instantiate, from another file you must clarify to which namespace you are referring to

That's why right after including the file we do use model\Product because we say that the newly included file uses the class that is in namespace model

With the above you should already be showing the result

UPDATE

Consider that by doing the following, class Demo automatically returns from the context of stackover because it is the namespace that surrounds it

<?php

namespace stackover;

class Demo
{

}

Therefore from a second file to access this class, if we do this

<?php

require "Archivo1.php";

use stackover\Demo;

Check that to be able to make the relation of namespace \ Class is with the backslash or backslash

    
answered by 06.12.2018 / 03:08
source