PHP: how to scroll through the dynamic number of classes

I want to detect all objects (classes) defined in a php file (example: flavors.php). The number of objects will be determined dynamically, so I need to process the available objects using the function at runtime until the objects are exhausted. After the objects are exhausted, the program stops.

I have full control over the code, so if there is a better way to keep the variables and keep them organized using only php, please let me know.

As a learning experience, I am trying to get php to manipulate a set of objects without knowing the numbers or names of objects that exist in advance.

This is the logic I'm trying to encode:

while(THERE ARE STILL CLASSES TO PROCESS IN FLAVORS.php)
{
  $var = description_generator(CLASS_NAME SENT TO THE FUNCTION);
  print($var);
}

For context, this is the whole program:

flavors.php

class vanilla
{
    // property declaration
    public $color = 'white';
    public $price = '1.25';
}

class chocolate
{
    // property declaration
    public $color = 'brown';
    public $price = '1.50';
}

main.php
{
function description_generator($class_name)
{

    $selected_flavor_class = new $class_name();
    $flavor_color = $selected_flavor_class->flavor_color;
    $flavor_price = $selected_flavor_class->flavor_price;

    return "$flavor_color"."<br />"."$flavor_price";
}

while(THERE ARE STILL CLASSES TO PROCESS)
{
    print($var = description_generator(CLASS_NAME));
}

, PHP ? , , = "", "1.50", ?

+3
3

Zend_Reflection, API .

$r = new Zend_Reflection_File('flavors.php');
$classes = $r->getClasses();
echo "File holds " . count($classes) . ":\n";
foreach ($classes as $class) {
    echo $class->getName() . "\n";
}

Zend Framework use-at-will, - . Zend Framework Zend_Reflection.

, interface:

interface IFlavor
{
    public function getName();
    public function getPrice();
    public function getColor();
}

, , ,

$class->implementsInterface('IFlavor')

, Flavors. , , , TypeHint , .

, , Flavor , .

class Flavor implements IFlavor
{
    protected $_name;
    protected $_color;
    protected $_price;

    public function __construct($name, $color, $price)
    {
        $this->_name  = $name;
        $this->_color = $color;
        $this->_price = $price;
    }

    // getter methods
}

, Reflection flavors, Config . , , init Flavors . Flavors Value ( DDD), Flavor , .

+2

You need to keep the list of flavors in an array. Once they are in the array, you can scroll them and process them

$flavours = array('vanilla', 'chocolate');

foreach($flavours as $flavour) {
    echo description_generator($flavour);
}
0
source

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


All Articles