PHP: classes using each other

I have a parent class of Color and children, ColorRGBA and ColorHSLA. In the Color class I want to use static functions from these children, but I got the error β€œThe Color class was 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 can I rebuild the class hierarchy or include directives? Or is there any other way how to make my code work?

+4
source share
3 answers

To get around this problem, perhaps you should consider implementing a factory class. If this is not your style, another elegant way to solve this problem is to use __ autoload () .

Regarding code maintenance. It will be difficult depending on how many colors you enter. Why not try 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+

0
source

Yes in PHP there are no "forward declarations", as in C ++. Therefore class Color; not valid in PHP.

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

 class ColorRGBA extends Color 

runs before this line:

 class Color { 

So Color really undefined. To solve this problem, you can 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 defined only when isValid called.

You can also put include_once after defining the Color class.

+2
source

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

0
source

Source: https://habr.com/ru/post/1416432/


All Articles