I was just researching this for the past hour to try and figure out the best way to do this.
I'm working on a PHP CLI application that uses the following function to find the command line width.
function getColLen() {
$getcolLen = shell_exec('tput cols');
$colLen = (int) $getcolLen;
return $colLen;
}
Now, I have around 8 classes I'm working with right now, and this function I am using quite a bit -- in most classes and in a lot of methods within the classes.
Previously it was just included in a composer vendor autoload functions.php file and I was initializing it in each function, like
public function Tagger()
{
$colwidth = getColLen();
. . . . .
etc.
I researched many different options for using a dynamic global variable across PHP classes, out of which there are many and some get quite complicated.
For fun I decided to try and this to a CONSTANT in my functions.php file
define('CLIWIDTH', getColLen());
I did not think this would work, as all the information I read -- and all the examples I saw -- were about defining static variables such as a string or directory.
But to my surprise this works perfectly fine. A simple echo CLIWIDTH; anywhere brings in the command line width (tested with success for different outputs when launching the console at different sizes).
Is this not widely recognized as a proper way to create a dynamic variable across all files? Perhaps I wasn't searching the correct terms but I have never heard of someone using a function inside a defined constant such as this.
Is this proper code? Is there a reason why this isn't more recommended when discussing constants, globals, so forth?
define()can be.