[英]Why isn't this function executed at include time?
I am including a PHP file and that file should, I think, execute a function when included but it isn't.我包含一个 PHP 文件,我认为该文件应该在包含时执行一个函数,但事实并非如此。 Can you fill me in why its not executing and how I can make it execute?
你能告诉我为什么它不执行以及我如何让它执行吗?
<?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:用法:
// 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.
The reason is you are calling if (class_exists('Editor'))
which returns true
.原因是您正在调用
if (class_exists('Editor'))
返回true
。
Your main.php
file should look like:您的
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;
And your editor.php
file should look like:您的
editor.php
文件应如下所示:
// editor.php
class Editor {
public static function initialise() {
// do some initialisation ...
echo 'Yes, I am being called.';
}
}
Editor::initialise();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.