Я поигрался с CodeIgniter и, чтобы расширить свои знания PHP, я пытаюсь создать свой собственный фреймворк.
У меня проблема в том, что я хочу эквивалент функции CodeIgniter get_instance ().Но через все мои поиски я просто не могу понять это, и при этом я не знаю, использую ли я это даже в правильном контексте ..
Я верю, что я ищу, это шаблон синглтона, ноЯ просто не могу понять, как это реализовать, поэтому кто-нибудь может мне помочь?
Я хочу иметь возможность доступа к переменной $ page для каркаса из функции содержимого.
[Я хочу сказать, что это упрощенная версия, и моя кодировка обычно лучше, чем эта ..]
До редактирования:
<?php
class Framework {
// Variables
public $page;
function __construct()
{
// For simplicity's sake..
$this->page->title = 'Page title';
$this->page->content->h1 = 'This is a heading';
$this->page->content->body = '<p>Lorem ipsum dolor sit amet..</p>';
$this->output();
}
function output()
{
function content($id)
{
// I want to get an instance of $this
// To read and edit variables
echo $this->page->content->$id;
}
?>
<html>
<head>
<title><?php echo $this->page->title ?></title>
</head>
<body>
<h1><?php content('h1') ?></h1>
<?php content('body') ?>
</body>
</html>
<?php
}
}
new Framework;
После редактирования:
<?php
class Framework {
// Variables
public $page;
public static function get_instance()
{
static $instance;
$class = __CLASS__;
if( ! $instance instanceof $class) {
$instance = new $class;
}
return $instance;
}
function __construct()
{
// For simplicity's sake..
$this->page->title = 'Page title';
$this->page->content->h1 = 'This is a heading';
$this->page->content->body = '<p>Lorem ipsum dolor sit amet..</p>';
$this->output();
}
function output()
{
function content($id)
{
$FW = Framework::get_instance();
// I want to get an instance of $this
// To read and edit variables
echo $FW->page->content->$id;
}
?>
<html>
<head>
<title><?php echo $this->page->title ?></title>
</head>
<body>
<h1><?php content('h1') ?></h1>
<?php content('body') ?>
</body>
</html>
<?php
}
}
new Framework;