Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在Wordpress主题中使用自定义类_Php_Wordpress - Fatal编程技术网

Php 在Wordpress主题中使用自定义类

Php 在Wordpress主题中使用自定义类,php,wordpress,Php,Wordpress,我有一个PHP类,其中包含我想在主题中选择的任何地方使用的方法。例如,这个类: <?php class MyClass { const constant = 'constant value'; function showConstant() { echo self::constant . "\n"; } } $class = new MyClass(); $class->showConstant(); ?> 我将如何在我的

我有一个PHP类,其中包含我想在主题中选择的任何地方使用的方法。
例如,这个类:

<?php
class MyClass
{
    const constant = 'constant value';

    function showConstant() {
        echo  self::constant . "\n";
    }
}


$class = new MyClass();
$class->showConstant();

?>


我将如何在我的主题中包含这样一个类?

你有两种方法可以做到这一点;您可以编写一个插件,这可能有点过分,但您也可以:

1
functions.php
-文件中,只需在其中添加函数,然后就可以在主题中调用它们

function myClassFunction() {
  class MyClass {
    const constant = 'constant value';

    function showConstant() {
        echo  self::constant . "\n";
    }
  }

  $class = new MyClass();
  $class->showConstant();
}
2
在主题文件夹中创建一个新目录,类似于
/includes
。把你的班级放在那里。然后,在主题中需要类及其函数的地方,只需将其包含在模板中即可:

<?php
  require_once('includes/MyClass.php');
  $class = new MyClass();
  $class->showConstant();
?>

这完全取决于它是什么类型的类,它做什么,以及您使用它的频率。有很多方法可以做到这一点