I wanted to do some string abstractions in PHP today. I setup my configuration by defining the string templates as constants.
That looks great and like it would work, doesn’t it? It does not work. Why? Have you ever seen a tutorial or some code written by some else using a
$variable inside of a string intentionally?
$name = "Ryan"; echo "$name is awesome!";
That’s not right. It should be concatenated together because this is confusing. Is it printing $name or the variable in $name? None of the other languages I use do this kind of $inline variable inflation. It bothers me.
My code today was using sprintf to fill in the variables from the filename template established earlier.
$logfile = sprintf(LOG_FILENAME, $user, $date);
After doing some testing and noticing that my log files were coming up as -.txt, I realized there was a problem with the strings.
I looked over my template
"logs/%1$s-%2$s.txt" and saw the problem. The
$s were uninitialized variables being treated as empty strings! To fix the obvious problem of interpreted strings, I changed them to literals. That is, with single quotes:
That fixed the problem.