Reputation: 13693
I have a PHP class with methods that I would like to use anywhere I choose on my theme.
For instance this class:
<?php
class MyClass
{
const constant = 'constant value';
function showConstant() {
echo self::constant . "\n";
}
}
$class = new MyClass();
$class->showConstant();
?>
How would I include such a class in my theme?
Upvotes: 14
Views: 16539
Reputation: 2527
You have a couple of ways to go about this; you can write a plugin, which might be a bit overkill, but you can also:
1
In your functions.php
-file, just add your functions there, and then you can call them in your theme
function myClassFunction() {
class MyClass {
const constant = 'constant value';
function showConstant() {
echo self::constant . "\n";
}
}
$class = new MyClass();
$class->showConstant();
}
2
Create a new directory in your themes folder, something like /includes
. Put your class in there. Then wherever in your theme where you need your class and it's functions, just include it in your template:
<?php
require_once('includes/MyClass.php');
$class = new MyClass();
$class->showConstant();
?>
It all depends on what kind of class it is, what it does and how often you use it. There are a whole lot of ways to do it.
Upvotes: 21