За последние 24 часа нас посетили 22933 программиста и 1267 роботов. Сейчас ищут 799 программистов ...

Не запускается мини приложение

Тема в разделе "PHP для новичков", создана пользователем Nick_1, 15 окт 2021.

  1. Nick_1

    Nick_1 Новичок

    С нами с:
    15 окт 2021
    Сообщения:
    2
    Симпатии:
    0
    Таблица news в БД test как видно имеется и доступ к ней есть:

    https://cloud.mail.ru/public/gJrD/6b5pJkfXa
    PHP:
    1. <?php
    2. $dsn = 'mysql:host=127.0.0.1;dbname=test';
    3. $dbh = new PDO($dsn, 'root', '');
    4. $sth = $dbh->prepare('SELECT * FROM news');
    5. $sth->execute();
    6. $data = $sth->fetchAll();
    7. var_dump($data);
    Реузльтат при выводе инфы из БД:
    Код (Text):
    1.  
    2. array(3) { [0]=> array(8) { ["id"]=> string(1) "1" [0]=> string(1) "1" ["title"]=> string(50) "Большие слоны идут на север" [1]=> string(50) "Большие слоны идут на се-вер" ["lead"]=> string(0) "" [2]=> string(0) "" ["author_id"]=> string(1) "1" [3]=> string(1) "1" } [1]=> array(8) { ["id"]=> string(1) "2" [0]=> string(1) "2" ["title"]=> string(58) "Метеорит упал рядом с человеком" [1]=> string(58) "Метеорит упал рядом с человеком" ["lead"]=> string(0) "" [2]=> string(0) "" ["author_id"]=> string(1) "2" [3]=> string(1) "2" } [2]=> array(8) { ["id"]=> string(1) "3" [0]=> string(1) "3" ["title"]=> string(65) "Экономика оставляет желать лучшего" [1]=> string(65) "Экономика оставляет желать лучшего" ["lead"]=> string(0) "" [2]=> string(0) "" ["author_id"]=> string(1) "3" [3]=> string(1) "3" } }
    Файлы и папки:

    index.php
    PHP:
    1. <?php
    2. require __DIR__ . '/templates/news.php';
    3. ?>
    4. config.php
    5.  
    6. <?php
    7. return
    8. [
    9. 'host'=>'127.0.0.1',
    10. 'db_name'=>'test',
    11. 'username'=>'root',
    12. 'password'=>''
    13. ];
    14. ?>
    Папка templates:

    article.php
    PHP:
    1. <h2>
    2. <?php echo $this->data['record']->getHeadline();?>
    3. </h2>
    4. <p>
    5. <?php echo $this->data['record']->getFullText();?>
    6. </p>
    news.php
    PHP:
    1. <!doctype html>
    2. <html lang="ru">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport"
    6. content="width=device-width, user-scalable=no, initial-scale=1.0,
    7. maximum-scale=1.0, minimum-scale=1.0">
    8. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    9. <title>Новости</title>
    10. </head>
    11. <body>
    12. <h1>Главные новости</h1>
    13. <hr>
    14.  
    15. <?php
    16. foreach($this->data['news']->getNews() as $article)
    17. {
    18. $line = new View();
    19. $line->assign('article', $article);
    20. $line->display('newsAll.php');
    21. }
    22. ?>
    23. <hr>
    24. </body>
    25. </html>
    26.  
    27. newsAll.php
    28. <article>
    29. <h2>
    30. <a href="article.php?id=<?php echo $this->data['article']->getId(); ?>">
    31. <?php echo $this->data['article']->getHeadline(); ?>
    32. </a>
    33. </h2>
    34. <p>
    35. <?php echo $this->data['article']->getText(); ?>
    36. </p>
    37. </article>
    38. <hr>
    Папка: Classes

    Article.php:
    PHP:
    1. <?php
    2.  
    3. class Article
    4. {
    5. protected $id;
    6. protected $headline;
    7. protected $text;
    8. protected $fullText;
    9. protected $author;
    10. public function __construct($article)
    11. {
    12. $data = explode('|', $article);
    13. $this->id = ($data[0]);
    14. $this->headline = trim($data[1]);
    15. $this->text = mb_substr($data[2], 0, 150) . '...';
    16. $this->fullText = trim($data[2]);
    17. $this->author = trim($data[3]);
    18. }
    19.  
    20. public function getId()
    21. {
    22. return $this->id; .
    23. } //
    24. public function getHeadline()
    25. {
    26. return $this->headline;
    27. }
    28. public function getText()
    29. {
    30. return $this->text;
    31. }
    32. public function getFullText()
    33. {
    34. return $this->fullText;
    35. }
    36. public function getAuthor()
    37. {
    38. return $this->author;
    39. }
    40.  
    41. public function getLine()
    42. {
    43. return $this->headline . '|' . $this->text . '|' . $this->author;
    44. }
    45. }
    DB.php:
    PHP:
    1. <?php
    2.  
    3. class DB
    4. {
    5. protected $dbh;
    6.  
    7. public function __construct()
    8. {
    9. $this->connect();
    10. }
    11. private function connect()
    12. {
    13. $config = include __DIR__ . '/../config.php';
    14. $dsn = 'mysql:host='. $config['host'] . ';dbname='.$config['db_name'].';';
    15. $this->dbh = new PDO ($dsn, $config['username'], $config['password']);
    16. return $this;
    17.  
    18. public function execute($sql)
    19. {
    20. $sth = $this->dbh->prepare($sql);
    21. $res = $sth->execute();
    22. return $res;
    23. }
    24.  
    25. public function query($sql, $class)
    26. {
    27. $sth = $this->dbh->prepare($sql);
    28. $res = $sth->execute();
    29. if (false !== $res) {
    30. return $sth->fetchAll(\PDO::FETCH_CLASS, $class);
    31. }
    32. return [];
    33. }
    34. }
    35.  
    36. $db = new DB;
    37. $sql = 'SELECT * FROM news';
    38. $a = $db->execute($sql);
    39. ?>
    News.php:
    PHP:
    1. <?php
    2.  
    3. require __DIR__.'/Article.php';
    4.  
    5. class News
    6. {
    7.  
    8. protected $path;
    9. protected $data;
    10.  
    11. public function __construct($path)
    12. {
    13. $id = 0;
    14. $this->path = $path;
    15. $data = file($path, FILE_IGNORE_NEW_LINES);
    16. foreach ($data as $line) {
    17. $this->data[++$id] = new Article($line);
    18. }
    19. }
    20.  
    21. public function getData($id)
    22. {
    23. return $this->data[$id];
    24. }
    25.  
    26. public function getNews()
    27. {
    28. return $this->data;
    29. }
    30.  
    31. public function append(Article $text)
    32. {
    33. $this->data[] = $text;
    34. }
    35.  
    36. public function save()
    37. {
    38. $str = implode("\n", $this->data());
    39. file_put_contents($this->path, $str);
    40. }
    41.  
    42. public function getAll()
    43. {
    44. $data = [];
    45. foreach ($this->getData() as $record) {
    46. $data[] = $record->getLine();
    47. }
    48. return $data;
    49. }
    50. }
    51. ?>
    View.php:
    PHP:
    1. <?php
    2.  
    3. class View
    4. protected $data;
    5.  
    6. public function __construct()
    7. {
    8. }
    9.  
    10. public function assign(string $name, $value)
    11. {
    12. $this->data = [];
    13. $this->data[$name] = $value;
    14. }
    15.  
    16. public function display(string $template)
    17. {
    18. echo $this->render($template);
    19. }
    20.  
    21. public function render(string $template)
    22. {
    23. extract($this->data, EXTR_OVERWRITE);
    24. include $template;
    25. $content = ob_get_contents();
    26. return $content;
    27. }
    28. }
    29. ?>
    Результат:
    https://cloud.mail.ru/public/mhCB/Zqazy2EpS

    Т.е.: неустранимая ошибка: Неперехваченная ошибка: использование $ this вне контекста объекта

    От модератора: вставляй код с помощью кнопки </>
     
    #1 Nick_1, 15 окт 2021
    Последнее редактирование модератором: 15 окт 2021
  2. ADSoft

    ADSoft Старожил

    С нами с:
    12 мар 2007
    Сообщения:
    3.823
    Симпатии:
    736
    Адрес:
    Татарстан
    как то все странно....
    но суть ошибки вот в чем
    $this это зарезервированная переменная используемая ВНУТРИ класса/объекта, который обращается к этому самому классу
    вне класса/объекта ее не имеет смысла использовать - отсюда и ошибка.

    не понял вообще в каком месте у вас шаблон подключается и как
     
  3. Nick_1

    Nick_1 Новичок

    С нами с:
    15 окт 2021
    Сообщения:
    2
    Симпатии:
    0
    ок, спасибо, буду разбираться