Best way to define constants in my Wordpress theme

Viewed 1628

Is there a preferred way to define my constants that I will use in my theme?

1- Can I Define it as a method in my class?

<?php MyClass::templatename(); ?>

2- Or using define?

<?php define( 'TEMPLATE_NAME', 'mytheme' ); ?>
1 Answers

Creating a whole function for a single static value is not very efficient. Because of that, I would go with the define method. You could define this constant in a constant.php file, which would be imported by your theme's function.php.

You could also define a class constant, this could be interessting if your are defining a non-uniquely named constant, and you think this constant might leak somewhere else in the code. ( A good example would be a constant named DEBUG, because a similar constant is already defined and use elsewhere. )

You can define a class variable using the keyword const.

class MyClass {
    const TEMPLATE_NAME = 'some value';
}

// use it as such
echo MyClass::TEMPLATE_NAME;
Related