I’m on a mission to learn to be the best PHP developer that I can be and it would be very helpful if you could also explain why this is bad code (it seems bad to me, but I have no idea why) and what would be a better way of accomplishing the same thing.
There are two types of expert PHP developers, I have found. One type lives in an ivory palace and looks down their nose at beginners and coders that are trying to learn and improve and have nothing but disdain for us. Others are very helpful and willing to take the time to guide us and I find I learn a lot from their experience, and can improve my own practices as a result.
This would be an amazing thread if it were turned into a bit a learning tool for those of us who want to improve.
Not PHP, but I used to work with a guy in ColdFusion who liked to name common variables variable. It makes things especially difficult, because CF had error messages like There was a problem with the variable variable. The first time I ran into that, I was like “wtf is a variable variable? a pointer? CF has pointers? What?”.
I think I ended up leaving that code the way it was because I was afraid to touch it and just wrote an extension that bypassed it.
Hey WebMachine, it was absolutely not my intention to make fun of beginner coders - everyone has to start somewhere. I wouldn’t be participating on these forums if I didn’t believe in helping people who genuinely want to improve
What’s worrying is when you find code like that being written by people claiming to be professionals and charging for their work!
Great idea, if anyone comes across some snippets of bad code they can share it would be interesting to show how they could be refactored and improved.
In addition to mawburn’s method, if you prefer to use the DateTime object you can also get the current year like this:
// PHP >= 5.4
$curYear = (new DateTime())->format("Y");
// PHP < 5.4
$curDate = new DateTime;
$curYear = $curDate->format("Y");
Actually that can happen. I ran into an issue once where posts would report being posted an hour or two in the future. It happened because the db server and the web server were physically located in different time zones. The quick and dirty solution was to get NOW from the db so that we would always use a consistent timezone. But the better solution, which I recommend everone use, is to always use gmtime and gmdate rather than time and date. That way you’ll get a consistent result no matter what timezone your server is in.