Классы в PHP 8
| Пример | |
| __construct | |
| Похожие статьи |
Пример
Пример реализации класса
<?php
namespace Aredel\Demo;
class Page
{
public const LANG = 'ru';
private ?string $page_lang = null;
public function setPageLang(?string $page_lang = null)
{
if ($page_lang) {
$this->page_lang = $page_lang;
} else {
$this->page_lang = self::LANG;
}
}
public function getPageLang()
{
return $this->page_lang;
}
}
$page = new Page();
$page->setPageLang('en');
echo $page->getPageLang();
en
__construct()
__construct() - это один из так называемых магических методов (magic methods)
Его не нужно вызывать отдельно - он автоматически вызывается каждый раз
когда вы создаете новый объект класса с помощью new
Рассмотрим применение __construct() для создания страницы
Парк Палома в Бенальмадене
<?php
namespace Aredel\Demo;
class Page
{
public function __construct(
$lang,
$title,
$description,
$keywords,
) {
$this->description = $description;
$this->keywords = $keywords;
$this->lang = $lang;
$this->title = $title;
}
public function createHead()
{
return '<head>'
. '<title>' . $this->title . '</title>'
. '<meta name="description" content="' . $this->description . '">'
. '<meta name="keywords" content="' . $this->keywords . '">'
. '<meta http-equiv="content-type" content="text/html; charset=UTF-8">'
. '<link rel="stylesheet" type="text/css" href="/.css/heihei_style.css">'
. '</head>';
}
}
Теперь подключим этот класс к файлу Main.php
<?php
use Aredel\Demo\Page;
require_once 'Page.php';
$page = new Page(
lang: "ru",
title: "Парк Палома в Бенальмадене",
description: "Бесплатный парк с птицами и черепахами Коста-дель-соль",
keywords: "Парк Палома, Бенальмадена парк с животными, Бенальмадена пруд с черепахами"
);
echo $page->createHead();
Запустим Main.php
<head> <title>Парк Палома в Бенальмадене</title> <meta name="description" content="Бесплатный парк с птицами и черепахами Коста-дель-соль"> <meta name="keywords" content="Парк Палома, Бенальмадена парк с животными, Бенальмадена пруд с черепахами"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="/.css/heihei_style.css"> </head>
Автор статьи: Андрей Олегович
| Development with PHP | |
| OOP in PHP | |
| PHP 8 Classes | |
| Inheritance in PHP | |
| Methods from two sibling classes: traits |