2015-04-25 2 views
-1

Я создал тему class.I хочу добавить файл css в html head по методу addCss и отобразить с помощью метода displayCss.Как отобразить свойство метода вне класса

в моей теме класс я создал displayCss() метод для отображения кода css от addCss() метода, и я использую addCss для включения файла css. см head.phtml и index.php

проблема заключается в том, что он не отображает код CSS в head.phtml

еще один вопрос я называю класс шаблона в index.php почему я должен вызовите его еще раз в head.phtml. Если я не позвоню в head.phtml, я получу эту ошибку

> Undefined variable: theme in head.phtml 

спасибо.

Class Template { 

    public function __construct ($template_dir = null, $css_dir = null, $js_dir = null) { 

    if ($template_dir !== null) 
     $this->template_dir = $template_dir; 
    if ($css_dir !== null) 
     $this->css_dir = $css_dir; 
    if ($js_dir !== null) 
     $this->js_dir = $js_dir; 
} 

public function render ($template_file) { 

    if (file_exists ($this->template_dir.$template_file)){ 
     include $this->template_dir.$template_file; 
    } else { 
     throw new Exception ('template dosyalari eksik ' . $this->template_dir . $template_file ); 
    } 
} 

public function displayCss() { 
    echo $this->CSS; 
} 

public function htmlHead() { 
    self::render('head.phtml'); 
} 

public function addCss($css_file) 
{ 
    if (preg_match('/http/i', $css_file)) { 
     $this->CSS = sprintf('<link rel="stylesheet" href="%s">', $css_file); 
    }else{ 

     if (file_exists ($this->css_dir.$css_file) ) { 
      $this->CSS = sprintf('<link rel="stylesheet" href="%s">', $this->css_dir . $css_file); 
     } else { 
      $this->CSS = "css dosyasina ulasilamiyor"; 
     } 
    } 
    return $this->CSS; 
} 

} 

head.phtml

<?php $theme = new Template(); ?> 
<html> 
<title>Page</title> 

<?php $theme->displayCss(); ?> 

index.php

<?php 

require_once 'template.class.php'; 
$theme = new Template(); 

$theme->addCss('style.css'); 

$theme->htmlHead(); 
+0

Почему вы даете нисходящее движение? –

ответ

0

только разъяснение о классах и объектах различия. С self :: то, что мы называем статической функцией внутри определения класса. Когда мы вызываем функции или свойства объекта, изнутри определения класса, мы используем ключевое слово $ this. Поэтому функция HtmlHead() должен быть:

public function htmlHead() { 
    $this->render('head.phtml'); 
} 

Согласно вышесказанному, head.phtml должно быть:

<html> 
<title>Page</title> 

<?php $this->displayCss(); ?> 

Поскольку вы включили head.phtml в определении класса, когда вы звоните
$ theme-> HtmlHead(); И вам не нужно создавать новый объект Template.

Смежные вопросы