tipu
tipu

Reputation: 9604

cascading use namespace in php with child classes

I am using an aliased and namespaced class in a parent class successfully but it doesn't seem to be available in the child class. The actual error is from the autoloader. The weird thing is that the function does work in the parent class and loads fine. How can I make a class brought in by use available in subclasses?

edit: the recipes are stateless -- would it make sense to make them singletons in Base and then reference them as members in the child class MyTest?

I have the two files:

Base.php:

namespace selenium;
use selenium\recipe\Cms as Cms;
class Base extends \PHPUnit_Framework_TestCase
{
    public function __construct()
    {
        Cms::staticfunc(); //works fine
    } 
}

MyTest.php:

class MyTest extends \selenium\Base
{
    public testMyTest()
    {
        Cms::staticfunc(); //errors here 
    }
}

Upvotes: 3

Views: 1119

Answers (1)

Mike Purcell
Mike Purcell

Reputation: 19979

From comment:

i was hoping for a way to cascade the use without duplicating that line among the 20 or so child classes

That is one of the biggest issues I have with PHP namespacing, that you have to call use for every file the current script needs access to. It's the same situation we used to face having to call require_once 20 times on some scripts in order to bring in the necessary libraries.

What I prefer to do is namespace my files (as they reside on the filesystem, like Zend Framework does) and use an autoloader to avoid the whole mess. I currently use ZF autoloader, which can be used outside of the framework, or you can also use the vanilla PHP implementation using SplAutoload.

-- Update --

I have a library which I have written over the last few years which is namespaced as Hobis_Api, and are located on the filesystem with the same convention; ~/projects/projects/dp/hobis/lib/Hobis/Api/*. In order to register the namespace with Zend_Loader I do the following:

// Be sure to set the include path to include the Zend and Hobis_Api files
// Not sure how your setup is, but would look something like:
set_include_path(get_include_path() . ':' . DIRNAME(__FILE__));

require_once 'Zend/Loader/Autoloader.php';

$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace(
    array(
        'Hobis_Api_'
    )
);

Normally the above code would go into some bootstrap file, which you can call from a centralized script in order to register the autoloader, once.

Now, if your include path is set correctly, anytime you reference Hobis_Api_* it will be autoloaded for you, so you don't need to call use or require_once, example usage:

// SomeScript.php

// Notice no requires

// I can make a call to Hobis_Api_Image without error
$image = Hobis_Api_Image;
$image->setHeight(400);

Upvotes: 2

Related Questions