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
Related
So, I'm converting some old code into a namespace, and trying to get autoload working. I've managed to follow the many good answers on this site about how to account for the namespace part of an autoloaded class (How do I use PHP namespaces with autoload?) - no problem.
Here's a different wrinkle, though. How do I autoload classes within the same namespace?
My autoload function (defined in a global include) is something like this:
function app_autoload($class)
{
$path = __DIR__.'/'.str_replace("\\", DIRECTORY_SEPARATOR, $class).'.php';
if (file_exists($path))
{
require_once($path);
}
}
spl_autoload_register('app_autoload');
If I have a class defined in the namespace app\nstest, I can autoload it just fine from most of my system:
namespace app\nstest;
class Test1
{
function hello()
{
echo "Hello world";
}
}
However, another class in the same namespace has issues:
namespace app\nstest;
class Test2
{
function callMe()
{
$test1 = new Test1();
}
}
If I explicitly include/require the Test1 file at the top of Test2, no problems, but the autoloader doesn't seem to be aware of the namespace, so it's loading "Test1.php" instead of "app/nstest/Test1.php".
I also tried checking the __NAMESPACE__ inside the autoloader, but it's empty.
I have 5 scripts:
database.php
parent.php
child1.php
child2.php
somescript.php
parent.php class looks like this:
include 'database.php';
class Parent {
public $db;
function __construct() {
$this->db = new Database();
}
}
The child1.php and child2.php classes looks like this:
include 'parent.php';
class Child1 extends Parent {
function __construct() {
parent::__construct();
}
function useDb() {
$this->db->some_db_operation();
}
}
The problem
When I try to include both child1 and child2 in somescript.php, it returns the following error:
cannot declare class Database because the name is already in use in
database.php on line 4 (this is the line which contains words 'class Database')
But if I include only a single file (child1 or child2), it works great.
How do I correct that?
You want to use include_once() or require_once(). The other option would be to create an additional file with all your class includes in the correct order so they don't need to call includes themselves:
"classes.php"
include 'database.php';
include 'parent.php';
include 'child1.php';
include 'child2.php';
Then you just need:
require_once('classes.php');
try to use use include_onceor require_once instead of include or require
Another option to include_once or require_once is to use class autoloading. http://php.net/manual/en/language.oop5.autoload.php
You should use require_once and include_once. Inside parent.php use
include_once 'database.php';
And inside child1.php and child2.php use
include_once 'parent.php';
Class Parent cannot be declared because it is PHP reserved keyword so in effect it's already in use
I had this problem before and to fix this,
Just make sure :
You did not create an instance of this class before
If you call this from a class method, make sure the __destruct is set on the class you called from.
My problem (before) :
I had class : Core, Router, Permissions and Render
Core include's the Router class, Router then calls Permissions class, then Router __destruct calls the Render class and the error "Cannot declare class because the name is already in use" appeared.
Solution :
I added __destruct on Permission class and the __destruct was empty and it's fixed...
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
}
}
I created a class at Controller folder of Cake project like this:
<?php
class Hi
{
function __construct(){ }
public function hi()
{
echo "hi!";
exit;
}
}
Then in a controller, I tried to include it:
<?php
namespace App\Controller;
use App\Controller\AppController;
include_once "Hi.php";
class MyController extends AppController
{
public function sayHi()
{
$a = new Hi();
$a.hi();
}
}
Here is the error I'm having:
Fatal error: Cannot declare class Hi, because the name is already in use in path\api\src\Controller\Hi.php on line 2
What's going on?
MyController.php and Hi.php are in the same folder. I'm using PHP 7.
Including a file won't make the classes in that file part of the current namespace, as namespaces are a per-file functionality.
http://php.net/...namespaces.importing.php#language.namespaces.importing.scope
Your Hi class will be declared in the global namespace, and your new Hi() will cause PHP to look for it in the current namespace, ie it will look for App\Controller\Hi, which doesn't exist, hence the composer autoloader kicks in, and will map this via a PSR-4 namespace prefix match to src/Controller/Hi.php, which will include the file again, and that's when it happens.
http://www.php-fig.org/psr/psr-4/
Long story short, while using new \Hi() would fix this, you better not include class files manually, or declare them in paths where they do not belong. Instead declare your files and classes in a proper autoloading compatible fashion, that is for example with a proper namespace in a path that matches that namespace, like
namespace App\Utils;
class Hi {
// ...
}
in
src/Utils/Hi.php
I am using Symfony 2.4
I have a PHP file OAuth.php which has multiple classes inside that.
Code of OAuth.php is as below
<?php
namespace RT\AuthBundle\DependencyInjection\Vzaar;
use Exception;
class OAuthException extends Exception {
// pass
}
class OAuthConsumer {
//some code
}
class OAuthToken {
//some code
}
?>
I am inheriting above file in Vzaar.php file which is with in same namespace and it's code is as below
<?php
namespace RT\AuthBundle\DependencyInjection\Vzaar;
/*require_once 'OAuth.php';
require_once 'HttpRequest.php';
require_once 'AccountType.php';
require_once 'User.php';
require_once 'VideoDetails.php';
require_once 'VideoList.php';
require_once 'UploadSignature.php';*/
use RT\AuthBundle\DependencyInjection\Vzaar\OAuth;
use RT\AuthBundle\DependencyInjection\Vzaar\HttpRequest;
use RT\AuthBundle\DependencyInjection\Vzaar\AccountType;
use RT\AuthBundle\DependencyInjection\Vzaar\User;
use RT\AuthBundle\DependencyInjection\Vzaar\VideoDetails;
use RT\AuthBundle\DependencyInjection\Vzaar\VideoList;
use RT\AuthBundle\DependencyInjection\Vzaar\UploadSignature;
//use RT\AuthBundle\DependencyInjection\Vzaar\OAuth\OAuthConsumer;
Class Profile
{
public static function setAuth($_url, $_method = 'GET')
{
$consumer = new OAuthConsumer('', '');
//some code
}
}
?>
Creating new object of OAuthConsumer class throws error that
Fatal error: Class 'RT\AuthBundle\DependencyInjection\Vzaar\OAuthConsumer' not found in /var/temp/rt-web/src/RT/AuthBundle/DependencyInjection/Vzaar/Vzaar.php
1/1 ClassNotFoundException: Attempted to load class "OAuthConsumer" from namespace "RT\AuthBundle\DependencyInjection\Vzaar" in /var/temp/rt-web/src/RT/AuthBundle/DependencyInjection/Vzaar/Vzaar.php line 378. Do you need to "use" it from another namespace?
Because since 2.1 Symfony uses composer, and composer uses PSR-0/PSR-4 to autoloading the classes, you have to follow the namespace convention, so you have to create those classes in separate files and in the right directory structure, what is represented in the namespace.
EDIT
As Cerad mentioned in the comment, you can specify a class map in composer, although what is considered as a best practice with symfony projects, create every class in a separate file.