Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Definiowanie składowej poprzez objekt klasy
Raven1122
post
Post #1





Grupa: Zarejestrowani
Postów: 369
Pomógł: 2
Dołączył: 1.11.2010

Ostrzeżenie: (0%)
-----


Witam,

Mam pytanie, jak przekazać do klasy View składową, np.:

$this->view->title = 'Strona główna';

, a potem

wykorzystać tą składową w klasie View, np.:

echo $this->title;


Kawałki mojego kodu:

Klasa View

  1. <?php
  2.  
  3. class View {
  4.  
  5. function __construct() {
  6.  
  7. }
  8.  
  9. public function render($name){
  10. require BASE_URL.'views\\'.$name.'.php';
  11. }
  12.  
  13. }


Klasa nadrzędna kontrolera(każdy kontroler ją przedłuża):
  1. <?php
  2.  
  3.  
  4. class Controller {
  5.  
  6. function __construct() {
  7. $this->view = new View();
  8. }
  9.  
  10. }


i kontroller np. strony głównej

  1. <?php
  2.  
  3. class Index extends Controller{
  4.  
  5. function __construct() {
  6. parent::__construct();
  7. }
  8.  
  9. function index(){
  10. $this->view->render('index\index');
  11. $this->view->title = 'Strona główna';
  12. }
  13.  
  14. }
  15.  
  16. ?>


No i View strony głównej:
  1. <?php
  2.  
  3. require 'public/templates/header.php';
  4. ?>
  5. <hr />
  6. <?php
  7. echo $this->title;
  8. ?>
  9. <hr />
  10. <?php
  11. require 'public/templates/footer.php';
  12. ?>
  13.  


Po uruchomieniu strony głównej uzyskuje:

Notice: Undefined property: View::$title in D:\wamp\www\MVC\views\index\index.php on line 7

Proszę o pomoc (IMG:style_emoticons/default/smile.gif)
Z góry dziękuje.

Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
styryl
post
Post #2





Grupa: Zarejestrowani
Postów: 223
Pomógł: 27
Dołączył: 16.04.2008
Skąd: Bakutilu

Ostrzeżenie: (0%)
-----


Bardzo prosty przykład:

  1. class View
  2. {
  3. public function __construct( $filename )
  4. {
  5. $this->filename = $filename;
  6. }
  7.  
  8. public function set( $key, $value )
  9. {
  10. $this->_data[ $key ] = $value;
  11. }
  12.  
  13. public function render()
  14. {
  15. extract( $this->_data, EXTR_SKIP );
  16.  
  17.  
  18.  
  19. try
  20. {
  21. // Load the view within the current scope
  22. include $this->filename;
  23. }
  24. catch (Exception $e)
  25. {
  26. // Delete the output buffer
  27.  
  28. // Re-throw the exception
  29. throw $e;
  30. }
  31.  
  32. // Get the captured output and close the buffer
  33. return ob_get_clean();
  34. }
  35.  
  36. }
  37.  
  38. $view = new View('test.php');
  39. $view->set('test_var', 'działa');
  40. echo $view->render();
  41.  
  42. $view2 = new View('test2.php');
  43. $view2->set('test_var2', 'działa2');
  44. echo $view2->render();
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 16.10.2025 - 06:07