0

So I have a config.php file with the following:

use PHPOnCouch\Couch;
use PHPOnCouch\CouchAdmin;
use PHPOnCouch\CouchClient;

Then I have another file called let's say index.php that includes config.php

require_once("config.php");
include("page.php");

And then I have page.php that uses CouchClient like so:

$client = new couchClient ($URL, $DB);

But on page.php, I get the following error:

Fatal error: Class 'couchClient' not found in page.php

Shouldn't this page be connected to my config.php so that I don't have to put this in my page.php?

bryan
  • 8,879
  • 18
  • 83
  • 166
  • 2
    You need to add `use` in the file that is going to use those classes. The `use`-statements are not inherited.. – M. Eriksson Nov 15 '16 at 16:40
  • Okay thanks @MagnusEriksson - was hoping there was a way to make them inherited. – bryan Nov 15 '16 at 16:41
  • please refer this question http://stackoverflow.com/questions/10965454/how-does-the-keyword-use-work-in-php-and-can-i-import-classes-with-it – Sarath Kumar Nov 15 '16 at 16:43
  • No. If they were, it would be a mess, since you would have a lot of "you can't re-declare class xxx" and so on. – M. Eriksson Nov 15 '16 at 16:44

1 Answers1

3

Do in page.php:

$client = new \PHPOnCouch\CouchClient ($URL, $DB);

or

use PHPOnCouch\CouchClient;
$client = new CouchClient ($URL, $DB);

this also works

use PHPOnCouch\CouchClient as SomeOtherFunnyName;
$client = new SomeOtherFunnyName ($URL, $DB);

and read more about namespaces in php.

Little update to:

Shouldn't this page be connected to my config.php so that I don't have to put this in my page.php?

  • Every include has its own local namesless namespace or one/more named namespaces!
  • If no namespace is given, you have a namesless namespace. In other word you can always use namespace { /*code*/ } in a php script
  • If you are in a namespace , you have to include via use all needed classes. And because all files have its own namespace, you have to include it via use
  • The notation of namespaces in this way: namespace xyz; with no braces, is for files that holding only one namespace!

A simple exmaple (just one file):

    namespace a {
      class a {}
    }
    namespace b {
      use a\a;
      class b extends a{}
    }
    namespace {
      use a\a;
      use b\b;
      new a;
      new b;
    }

lets say the last namespace isnt given, and we include this in an new file, we can do

    namespace mynamespace;
    use a\a;
    use b\b as x;
    new a;
    new x;
JustOnUnderMillions
  • 3,741
  • 9
  • 12