Efficiency: setting a var or calling method? - php

Would it be more efficient to declare a var:
$datetime = Carbon::now();
and use the var in a method twice:
$toDate < $datetime && $fromDate > $datetime
Or set no var and call something like Carbon::now() twice:
$toDate < Carbon::now() && $fromDate > Carbon::now()

I would follow the DRY principle and follow the first solution:
$datetime = Carbon::now();
if ($toDate < $datetime && $fromDate > $datetime) ...
In theory, method calling could be slightly more expensive due to pushing/popping context from the stack. However, I think the difference is negligible.
Someone brought up a valid point about race conditions that could occur if you call now() method twice. The second call may return a different value than the first call.

The answer and almost everything in the programming world depends on 2 things- Time and Space and every programmer has to choose one between them when it comes to optimisation.
These 2 things are the time taken to execute a program and Space (memory) used during the execution.
So your question which is whether to save the value of Carbon::now() in a variable or call it directly depends on what you want to optimise. Time or the space.
If your php script would have been very long i.e. took more time, then it is good to call the function once and save its value to save execution time i.e. use -
$datetime =Carbon::now();
Whereas, if you wanted your program to minimise the usage of memory, which seems obvious for servers because they need to respond to multiple requests simultaneously, you can directly call the method.
But again, you can optimise only one thing either time or memory. So choose the one that you want to achieve.

Related

php while loop where functions are ran based on time of day

I have created two functions in a separate php file and want them to run over and over.
After function A completes, I want it to compare the current time, relative to the last time function B ran, and if more than 24hrs has elapsed (or whatever value I set it to), it runs function B, resets the next time for when it should be trigger to run, and continues to run function A. They need to run separately and not parallel since values altered in function A will affect function B and thus need to be separate. The ideal scenario is I have a config.php file where I set the time delay (in hours), but I can sort that out later!
I am stumped on how to get this while(true){} loop organized... any ideas?
Regardless of whether you end up doing it this way (because I think the comments about cron make some good points, and there are some other issues you may run into with a continuously running PHP script like this) here's a basic logic for executing the alternate function based on a defined delay.
// define the delay and initialize the timestamp
$delay = 86400; // 24 hours, for example
$last_time = time();
while (true) {
functionA();
// the next time functionB should execute is the timestamp for the last run + the delay
if (time() > $last_time + $delay) {
functionB();
$last_time = time(); // reset the timestamp
}
}
Would something of this nature be similar to what you're looking for?
while ($time > 13 && $time < 21)
You could have flags involved in each function as well. If a boolean flag is fired and is = 1, then continue on?

How to match string values of datetime format in both Jquery and PHP?

For example -
In Jquery using the function (new Date()).getTime() am getting current datetime as 1470291303352.
But In PHP using strtotime(date('H:i:s')) am getting it as 1470291299.
Here i need to get the same string values. How to do it?
Firstly, php returns the number of seconds since 1970/01/01, jquery returns a number of milliseconds, so there is no way to be the same value.
Second - even if you've got the fastest server in the world it comes to the milliseconds in the execution of lines of code. So exactly the same value can hardly be achieved :)
What you can do to try to trim jquery for the last three numbers representing the milliseconds (this of course if you do these two lines of code to execute in one second :))
And for last, there is a issue of clocks on your server and client computer - it must be exactly the same.
The javascript method getTime() returns microseconds (http://www.w3schools.com/jsref/jsref_gettime.asp) whereas PHP time() (or in your case strtotime() http://php.net/manual/en/function.strtotime.php) returns seconds. The first depends on your clients clock, the latter on your servers clock...
Mostly you never will get the same timestamps this way... maybe you could work around using some kind of AJAX api to have the same timestamp on both sides...
Check this :
In php:
echo strtotime(date('H:i:s')); // 1470294647
In Script :
var date = new Date();
var d = Date.parse("'"+date+"'")/1000; // 1470294647
alert(d);

Change DateTime() offset in PHP

Is it possible in PHP to change the DateTime() to a custom time difference. Like adding it 20 min and everytime I call new DateTime() I would get those extra 20 min to the current date.
I thought about __construct() but didn't see how to fix it.
I can use a function of course, but just curious to know if its possible to change the prototype new DateTime()
Yes, it's possible:
$date = new DateTime();
$date->modify("+20 minutes"); //or whatever value you want
Example online
Ilia Rostovtsev's answer is a good one for achieving your goal. Alternatively you can also use the DateInterval class with DateTime::add(). Personally, I prefer that one because you don't need to know how strings need to look like while DateInterval uses a standard like P1d for a day.
I wouldn't use inheritance to get a DateTime class including your wished behaviour. Instead you can create some kind of factory which contains Ilia's code (and every other code that is part for the object creation). The interval can be added as parameter. Your added interval, your 20 minutes should be stored in a constant in case you need to change that interval in the future while technically being able to use other intervals than 20 minutes.
You can do this all in one line:-
$date = (new \DateTime())->add(new \DateInterval('PT20M'));
That would be my preferred way of doing it.
See it working in PHP >= 5.3

Stepping through countdowns, unsure how to do this

I have a somewhat working countdown script already with a defined time (using new DateTime) but haven't figured out how to automatically swap times daily.
I'm looking to do a countdown every day at 5:10, 5:50, and 6:15 PM UTC. If 5:10:00 passes, then swap the countdown for 5:50:00. If it's 6:16, then it'll show for 5:10 tomorrow
How would I be doing comparisons for this? It says something about a non-object when I try to just use the datetime'd variable in a > <
Rather than comparing the objects themselves, you can compare their timestamps. For example:
if($dateTime1->getTimestamp() > $dateTime2->getTimestamp()) {
// ...
}

PHP DateTime for .NET developers

PHP's DateTime class has the two methods add() and sub() to add or subtract a time span from a DateTime object. This looks very familiar to me, in .NET I can do the same thing. But once I tried it, it did very strange things. I found out that in PHP, those methods will modify the object itself. This is not documented and the return value type indicates otherwise. Okay, so in some scenarios I need three lines of code instead of one, plus an additional local variable. But then PHP5's copy by reference model comes into play, too. Just copying the object isn't enough, you need to explicitly clone it to not accidently modify the original instance still. So here's the C# code:
DateTime today = DateTime.Today;
...
if (date < today.Add(TimeSpan.FromDays(7)) ...
Here's the PHP equivalent:
$today = new DateTime('today');
...
$then = clone $today;
$then->add(new DateInterval('P7D'));
if ($date < $then) ...
(I keep a copy of today to have the same time for all calculations during the method runtime. I've seen it often enough that seconds or larger time units change in that time...)
Is this it in PHP? I need to write a wrapper class for that if there's no better solution! Or I'll just stay with the good ol' time() function and just use DateTime for easier parsing of the ISO date I get from the database.
$today = time() % 86400;
...
if ($date < $today + 7 * 86400) ...
Time zones not regarded in these examples.
Update: I just found out that I can use the strtotime() function as well for parsing such dates. So what's the use for a DateTime class in PHP after all if it's so complicated to use?
Update^2: I noticed that my $today = ... thing above is garbage. Well, please just imagine some correct way of getting 'today' there instead...
It looks like you will definitely have to make a clone of the object. There does not seem to be a way to create a copy of the DateTime object any other way.
As far as I can see, you could save one line:
$today = new DateTime('today');
...
$then = clone $today;
if ($then->add(new DateInterval('P7D')) < $then) ...
I agree this isn't perfect. But do stick with DateTime nevertheless - write a helper class if need be. It is way superior to the old date functions: It doesn't have the year 2038 bug, and it makes dealing with time zones much, much easiert.

Categories