Using PHP Namespace in hierarchy directory structure Error - php

I am working with a folder structure as follows:
classes
-common.php
-core.php
modules
-index/index.php
I am trying to use the common.php in my index.php file and I am facing error:
Fatal error: Class 'classes\Common' not found in
D:\xampp\htdocs\devmyproject\modules\index\index.php on line 7
My Code:
commom.php class:
**Directory:/root/classes/common.php**
<?php
namespace classes;
class Common
{
function __construct()
{
}
}
My index.php file which try to use the classes/commom.php
**Directory:/root/modules/index/index.php**
<?php
namespace modules\beneficiary;
use \classes as hp;
include_once 'config.php';
$common = new \classes\Common();
//To Get Page Labels
$labels = $common->getPageLabels('1');
I am includeing common.php in config.php
$iterator = new DirectoryIterator($classes);
foreach ($iterator as $file) {
if ($file->isFile())
include_once 'classes/' . $file;
}
My Try:
It works fine when I use the folder structure as follows:
classes
-common.php
-core.php
modules
-index.php
If I use another folder inside modules it get error? I am not sure about he hierarchy of folders when using namespace can some one help me?

You have to either include common.php in index.php (better: use one of its relatives include_once or require_once) or set up an autoloader using spl_autoload_register() (or, not recommended, writing an __autoload() function).

Related

How to use namespace and use in PHP?

I have file index.php in directory Main;
There are also directory Helpers inside Main with class Helper.
I tried to inject class Helpers\Helper in index.php as:
<?
namespace Program;
use Helpers\Helper;
class Index {
public function __construct()
{
$class = new Helper();
}
}
But it does not work.
How to use namespace and use in PHP?
With Your Description, Your Directory Structure should look something similar to this:
Main*
-- Index.php
|
Helpers*
--Helper.php
If You are going by the book with regards to PSR-4 Standards, Your Class definitions could look similar to the ones shown below:
Index.php
<?php
// FILE-NAME: Index.php.
// LOCATED INSIDE THE "Main" DIRECTORY
// WHICH IS PRESUMED TO BE AT THE ROOT OF YOUR APP. DIRECTORY
namespace Main; //<== NOTICE Main HERE AS THE NAMESPACE...
use Main\Helpers\Helper; //<== IMPORT THE Helper CLASS FOR USE HERE
// IF YOU ARE NOT USING ANY AUTO-LOADING MECHANISM, YOU MAY HAVE TO
// MANUALLY IMPORT THE "Helper" CLASS USING EITHER include OR require
require_once __DIR__ . "/helpers/Helper.php";
class Index {
public function __construct(){
$class = new Helper();
}
}
Helper.php
<?php
// FILE NAME Helper.php.
// LOCATED INSIDE THE "Main/Helpers" DIRECTORY
namespace Main\Helpers; //<== NOTICE Main\Helpers HERE AS THE NAMESPACE...
class Helper {
public function __construct(){
// SOME INITIALISATION CODE
}
}

Why does PHP not find my class within the namespace

I basically have the following directory structure
MiniCrawler
Scripts/
htmlCrawler.php
index.php
This is the index.php
use Scripts\htmlCrawler;
class Main
{
public function init()
{
$htmlCrawler = new htmlCrawler();
$htmlCrawler->sayHello();
}
}
$main = new Main();
$main->init();
And this is the /Scripts/htmlCrawler.php
namespace Scripts;
class htmlCrawler
{
public function sayHello()
{
return 'sfs';
}
}
The code throws the following error
Fatal error: Class 'Scripts\htmlCrawler' not found in
/mnt/htdocs/Spielwiese/MiniCrawler/index.php on line 9
You forgot to include the file /Scripts/htmlCrawler.php in your index.php file.
require_once "Scripts/htmlCrawler.php";
use Scripts\htmlCrawler;
class Main
{
public function init()
{
$htmlCrawler = new htmlCrawler();
$htmlCrawler->sayHello();
}
}
$main = new Main();
$main->init();
Your index file cannot find the definition of the htmlCrawler file if you never provide the file defining this class, and the use of namespaces doesn't automatically include the required classes.
The reason why frameworks don't require you to include manually the file and you can simply add the use statement is because they're handling the inclusion of required classes for the developer. Most of the frameworks are using composer to handle the automatic inclusion of the files.
You can obtain a somewhat similar functionality using autoloading.

Class 'app\routing' not found

I'm currently building an application that will require a few different name spaces, however most of the application I want to put under the app namespace.
In my index.php file I declared to use the app namespace, however PHP still insists my class cannot be found like so...
<?php
define('PATH',strtok ( $_SERVER['REQUEST_URI'] , '?' ));
define("ROOT",$_SERVER['DOCUMENT_ROOT'].'/',true);
require 'vendor/autoload.php';
require 'app/class_loader.php';
use Carbon\Carbon;
use app\routing;
$routing = new routing;
$routing->router();
and inside my routing class I declare it as part of the app namespace like this
<?php
namespace app;
class routing
{
However I keep getting Fatal error: Class 'app\routing' not found in /var/www/my_app/index.php on line 15
This is my autoload file
<?php
function autoload_class_multiple_directory($class_name)
{
# List all the class directories in the array.
$array_paths = array(
'app/controllers',
'app/models',
'app/services',
);
foreach($array_paths as $path)
{
$file = $path.'/'.$class_name.'.php';
if(is_file($file))
{
include $file;
}
}
}
spl_autoload_register('autoload_class_multiple_directory');
I thought this is how namespaces worked? I want to ensure I make my application as easy to follow and code in from the get-go, could somebody please help point me in the right direction?
cheers!

PHP Composer Autoloader Class not Found Exception

The title speaks itself. So here is my project structure:
|src
|Database
|Core
|MySQL.php
|Support
start.php
|vendor
composer.json
index.php
MySQL.php file:
<?php
namespace Database\Core;
//Some methods here
index.php and start.php files:
//start.php file
<?php
require __DIR__ . '/../vendor/autoload.php';
?>
//index.php file
<?php
use Database\Core;
require __DIR__ . '/src/start.php';
$mysql = new MySQL(); // Gets exception Class 'MySQL' cannot found etc.
?>
And finally my composer.json autoload part:
"autoload": {
"psr-4": "Database\\": "src/" // Also tried "src/Database" too
}
Where is the problem? I'm really tired of trying to cope with this situation. Please help guys! Thanks.
You need to include namespace when you are initializing a class:
$mysql = new Database\Core\MySQL();
or
use Database\Core\MySQL;
$mysql = new MySQL();
See Using namespaces: Aliasing/Importing
Aside from not using the right use statement as already mentioned, PSR-4 does not work like that. It is more of an alias. You are essentially saying that src equals Database. So to have a directory named Database in there would imply that the fully qualified namespace + class equals 'Database\Database\Core\MySQL`. You want to use PSR-0 in this case, or adjust your PSR-4 definition.

call different namespace or class from one in PHP

on index.php I have below code
require 'Bootstrap.php';
require 'Variables.php';
function __autoload($class){
$class = str_replace('Control\\', '', $class);
require_once 'class/'.$class.'.php';
}
$bootstratp = new Control\Bootstrap();
on Bootstrap.php
namespace Control;
class Bootstrap{
function __construct(){
Constructor::load_html();
self::same_namespace_different_class();
}
static function same_namespace_different_class(){
Variables::get_values();
}
}
in class/Constructor.php
class Constructor{
static function load_html(){
echo 'html_loaded';
}
static function load_variables(){
echo 'load variables';
}
}
and on Variables.php
namespace Control;
class Variables{
static function get_values(){
Constructor::load_variables();
}
}
Assume, In total I have 4 PHP files including 3 Class files of 2 different namespaces. I also have a __autoload function on index.php that will call classes from 'class' folder but my 'Control' namespace files are in root folder.
When I echo the class name in __autoload i get the all the class names starting with 'Control\' even when I am calling a class from global namespace.
I am getting below error
Warning: require_once(class/Variables.php): failed to open stream: No such file or directory in _____________ on line 10
what is wrong with my code??
When I echo the class name in __autoload i get the all the class names starting with 'Control\' even when I am calling a class from global namespace.
This is because in Bootstrap.php all the code is in Control namespace (namespace Control). So when you use:
Variables::get_values();
you call
\Control\Variables::get_values();
if you want to use Variables from global namespace you should use here:
\Variables::get_values();
Of course, the same happens for in Variables.php file:
Constructor::load_variables();
As Constructor is defined in global namespace (in class/Constructor.php there is no namespace used), you should access it here using:
\Constructor::load_variables();
If it's still unclear you could also look at this question about namespaces in PHP.
You should also notice that using __autoload is not recommended. You should use spl_autoload_register() now. Documentation about autoloading

Categories