Данные не выводятся в select

<?php

namespace app\controllers;

use app\models\AppModel;
use app\widgets\currency\Currency;
use ishop\App;
use ishop\base\Controller;
use ishop\Cache;

class AppController extends Controller{

    public function __construct($route){
        parent::__construct($route);
        new AppModel();
        App::$app->setProperty('currencies', Currency::getCurrencies());
        App::$app->setProperty('currency', Currency::getCurrency(App::$app->getProperty('currencies')));
    }

}


 <select name="valuta">
           <?php new \app\widgets\currency\Currency();?>
        </select>   
    
    
      <option value=""><?=$this->currency['code'];?></option>
        <?php foreach($this->currencies as $k => $v): ?>
            <?php if($k != $this->currency['code']): ?>
                    <option value="<?=$k;?>"><?=$k;?></option>
                <?php endif; ?>
        <?php endforeach; ?>
        
        
        
        
        
         <?php
            
            namespace app\widgets\currency;
            
            use ishop\App;
            
            class Currency{
            
                protected $tpl;
                protected $currencies;
                protected $currency;
            
                public function ___construct(){
                    $this->tpl = __DIR__ . '/currency_tpl/currency.php';
                    $this->run();
                }
            
                protected function run(){
                    $this->currencies = App::$app->getProperty('currencies');
                    $this->currency = App::$app->getProperty('currency');
                    echo $this->getHtml();
                }
            
                public static function getCurrencies(){
                    return \R::getAssoc("SELECT code, title, symbol_left, symbol_right, value, base FROM currency ORDER BY base DESC");
                }
            
                public static function getCurrency($currencies){
                    if(isset($_COOKIE['currency']) && array_key_exists($_COOKIE['currency'], $currencies)){
                        $key = $_COOKIE['currency'];
                    }else{
                        $key = key($currencies);
                    }
                    $currency = $currencies[$key];
                    $currency['code'] = $key;
                    return $currency;
                }
            
                protected function getHtml(){
                    ob_start();
                    require_once $this->tpl;
                    return ob_get_clean();
                }
            
            }

Ответы (1 шт):

Автор решения: Егор Банин

Вы что-то всё перемешали. У вас должно быть как минимум 3 файла:

  • файл с классом;
  • файл шаблона;
  • файл контроллера, который вызовет ваш класс.

Я уберу особенности вашего фрэймворка и покажу как это работает в упрощённом виде.

Структура будет такая:

.
├── Currency.php
├── currency.tpl.php
└── index.php

Currency.php

<?php declare(strict_types=1);

class Currency {

    private string $currency;
    private array $currencies;

    public function __construct() {
        // предположим из кук и бд вы получили такие данные
        $this->currency = 'RUB';
        $this->currencies = [
            ['code' => 'EUR'],
            ['code' => 'USD'],
            ['code' => 'RUB'],
        ];
    }

    function getHtml(string $tpl): string {
        ob_start();
        require $tpl; // тут нельзя использовать requre_once, при повторном вызове он не подключит файл

        return ob_get_clean();
    }
}

currencies.tpl.php

<?= htmlspecialchars($this->currency) ?>
<select>
    <?php foreach($this->currencies as $c): ?>
        <?php if ($c['code'] !== $this->currency): ?>
            <option value="<?= htmlspecialchars($c['code']) ?>"><?= htmlspecialchars($c['code']) ?></option>
        <?php endif ?>
    <?php endforeach ?>
</select>

index.php

<?php declare(strict_types=1);

require 'Currency.php';
$c = new Currency;
echo $c->getHtml('currency.tpl.php');

Так всё сработает как надо. А ваш код может не работать по самым разным причинам. Вот проблемы, которые я заметил:

  • кривой html — option за пределами select
  • обращение через $this класса AppController к полям, которые определены в классе Currency
  • require_once вместо require

Скорее всего у вас отключены варнинги и php просто не показывает, что код написан неправильно. Включите варнинги, настроив error_reporting и display_errors.

→ Ссылка