user1440369
user1440369

Reputation: 43

PHP: classes using each other

I have parent class Color and children, ColorRGBA and ColorHSLA. In class Color I want to use a static functions from these children, but I got error "Class 'Color' not found." Here is the same problem http://forums.codeguru.com/showthread.php?t=469995 but class Color; doesn't seem to work in PHP.

Color.php:

include_once 'ColorRGBA.php';
include_once 'ColorHSLA.php';

class Color{
    public static function isValid(&$tokens, $i) {
        return ColorRGBA::isValid($tokens, $i) || ColorHSLA::isValid($tokens, $i);
    }
}

ColorHLSA.php and similarly ColorRGBA.php

include_once 'Color.php';

class ColorRGBA extends Color {
    public static function isValid(&$t, &$i) {
        ...
    }
}

How should I rebuild my class hierarchy or include directives? Or is there any other option how to make my code work?

Upvotes: 4

Views: 377

Answers (3)

afuzzyllama
afuzzyllama

Reputation: 6548

To get around this type of problem, perhaps you should think about implementing a factory class. If that isn't your style, another elegant way around this issue is it use __autoload().

As for the maintenance of the code. It is going to be difficult depending on how many colors you introduce. Why not trying something like:

class Color{
    public static function isValid($type, &$tokens, $i){
        $class_name = 'Color'.$type;            
        if (!class_exists($class_name)) {
            throw new Exception('Missing '.$class_name.' class.');
        }

        $class_name::isValid(&$tokens, $i);
    }
}

PHP 3.5+

Upvotes: 0

vstm
vstm

Reputation: 12537

Yes in PHP there are no "forward declarations" like in C++. That's why class Color; is invalid in PHP.

Now why do you get "Class 'Color' not found."? The problem is that, this line

class ColorRGBA extends Color

gets executed before that line:

class Color {

So Color is indeed not defined. To solve this you could do the following:

class Color{
    public static function isValid(&$tokens, $i) {
        include_once 'ColorRGBA.php';
        include_once 'ColorHSLA.php';
        return ColorRGBA::isValid($tokens, $i) || ColorHSLA::isValid($tokens, $i);
    }
}

This works because the Color class is now fully defined and the ColorRGBA/ColorHSLA classes are defined only when isValid gets called.

You could also put include_once after the definition of the Color class.

Upvotes: 2

robonerd
robonerd

Reputation: 198

You cannot include ColorRGBA.php in Color.php and Color.php in ColorRGBA.php. You will get circular dependency. This is why you get class not found error.

Upvotes: 0

Related Questions