我包含一个PHP文件,我认为该文件应在包含时执行一个函数,但事实并非如此。您能回答我为什么它不执行以及如何使其执行吗?
<?php
// editor.php
if (class_exists('Editor'))
return;
class Editor {
public static function initialise() {
// do some initialisation ...
}
}
Editor::initialise(); // this function doesn't appear to execute
// Alternate approach: which also doesn't seem to execute
function editor_init() {
Editor::initialise();
}
editor_init();
用法:
// Usage
<?php
// main.php
require_once('editor.php'); // here I expect my initialise() function be executed but it isn't.
// Alternate approach
include_once('editor.php'); // here I expect my initialise() function be executed but it isn't.
// Alternate approach
include('editor.php'); // here I expect my initialise() function be executed but it isn't.
答案 0 :(得分:0)
原因是您正在呼叫if (class_exists('Editor'))
并返回true
。
您的main.php
文件应如下所示:
// main.php
if (class_exists('Editor')):
return;
else:
require_once('editor.php'); // here I expect my initialise() function be executed but it isn't.
endif;
您的editor.php
文件应如下所示:
// editor.php
class Editor {
public static function initialise() {
// do some initialisation ...
echo 'Yes, I am being called.';
}
}
Editor::initialise();