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

Banner image

__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

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: