Classes in PHP 8
| Example | |
| __construct | |
| Related articles |
Example
Example class implementation
<?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() is one of the so-called magic methods
No need to call it separately - it is called automatically every time
you create a new class object with new
Consider using __construct() to create a page
Paloma Park in Benalmadena
<?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>';
}
}
Now connect this class to a file Main.php
<?php
use Aredel\Demo\Page;
require_once 'Page.php';
$page = new Page(
lang: "ru",
title: "Paloma Park in Benalmadena",
description: "Free park with birds and turtles on Costa del Sol",
keywords: "Paloma Park, Benalmadena animal park, Benalmadena turtle pond"
);
echo $page->createHead();
Run it Main.php
<head> <title>Paloma Park in Benalmadena</title> <meta name="description" content="Free park with birds and turtles on Costa del Sol"> <meta name="keywords" content="Paloma Park, Benalmadena animal park, Benalmadena turtle pond"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="/.css/heihei_style.css"> </head>
Article author: Andrei Olegovich
| Development with PHP | |
| OOP in PHP | |
| PHP 8 Classes | |
| Inheritance in PHP | |
| Methods from two sibling classes: traits |