Reputation: 69
What am I doing wrong here?
PHP Fatal error: Call to a member function add() on a non-object in
$rndM = rand(48,51);
$rndS = rand(1,59);
$ts = new DateTime($krow['GLSTRT']);
$tsd = $ts->format('Y-m-d H:i:s');
$tsup = 'PT'.$rndM.'i'.$rndS.'s';
$lamDate= $tsd->add(new DateInterval('\''.$tsup.'\''));
$krow['GLSTRT']
is a data value from MSSQL.
At first I was getting format errors with the add(new DateInterval)
.
I added in the format line, which resolved the format error and now the add(new DateInterval)
is throwing the error at the beginning of this post.
Upvotes: 1
Views: 857
Reputation: 69
:banghead: Thank you guys. This is what I get for rushing a fix. Here's the final product.
$ts = new DateTime($krow['GLSTRT']);
$intervalString = 'PT' . $rndM . 'M' . $rndS . 'S';
$ts ->add(new DateInterval($intervalString));
$lamDate = $ts->format('Y-m-d H:i:s');
Upvotes: 0
Reputation: 41756
The DateTime->format()
has the following method signature:
public string format ( string $format )
. It returns a string.
You don't need to reassign the DataTime object to work with it.
I've modified the order of the code and the variable names a little bit to make things clear:
// create new datetime object and return formatted date
$date = new DateTime($krow['GLSTRT']);
echo $date->format('Y-m-d H:i:s') . "\n";
// define interval string and create a new DateInterval object
$rndM = rand(48,51);
$rndS = rand(1,59);
$intervalString = 'PT' . $rndM . 'i' . $rndS . 's';
$intervalObject = new DateInterval($intervalString);
// add interval to date object
$date ->add($intervalObject);
// return the modified value formatted
echo $date->format('Y-m-d H:i:s') . "\n";
Upvotes: 1
Reputation: 91734
A few things:
format()
returns a string, so you cannot use add()
on the result as it is not an object. You need $ts->add()
instead.DateInterval
constructor; at the very least you need to get rid of the quotes around your string.add()
method, you modify your object, so assigning it to another variable is pointless unless you clone it first. Now both $ts
(see my first point) and $lamDate
will reference the same object.Upvotes: 2