为什么在包含时不执行此功能?

时间:2020-03-23 03:27:43

标签: php

我包含一个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.

1 个答案:

答案 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();