Calling a method as an argument

Is it possible to use the return value of a method as an argument of a function?
Like the method “format()” below:

echo htmlspecialchars($joke['jokedate']->format('jS F Y'),ENT_QUOTES,'UTF-8');

If not, please say why, TYIA.
P.S: I tried it and currently gives this error: Error: Call to a member function format() on string…

Looking at that, $joke is an array.
format() is a method belonging to a class.
The entry in the $joke array with the index jokedate is an object of the same class that format() belongs to.
Is that all correct?

I guess not, I think jokedate is a string, not an object. But you are trying to call a function on that string as if it were an object with the format() method in its class.

3 Likes

This will work as expected:

$joke = ['jokedate' => new DateTime('now')];

echo htmlspecialchars($joke['jokedate']->format('jS F Y'),ENT_QUOTES,'UTF-8');

As @SamA74 pointed out, most likely your $joke[‘jokedate’] is a string and not a DateTime object.

2 Likes

Yes, I forgot the point that most values in MySQL are typed as strings. Dates are also the same. Thanks to both of you.

Dates can be objects, though the date data may often start life as a string, either pulled form a database or coming from form data.

1 Like

Aha, thanks, so… If I get it right, then I’m going to ask this: In what example scenario might it really be initiated using a Date literal and not using a string?

Just like the example from @ahundiak:-

That creates a datetime object, then the function will work.

2 Likes

So if you want to use dates from the database as objects then you need to convert them to objects. It’s actually very simple:

// let's assume $joke['jokedate'] contains
// date string from db like '2018-02-18':
$joke['jokedate'] = new DateTime($joke['jokedate']);
echo htmlspecialchars($joke['jokedate']->format('jS F Y'),ENT_QUOTES,'UTF-8');
3 Likes

No doubt the date format will be used in more than one place and will change so I would create a function:

//==============================================
// Usage:
// echo sPrettyDate ();
// echo sPrettyDate ( FALSE, TRUE);
// echo sPrettyDate (FALSE, FALSE, 'Good morning');
//==============================================
function sPrettyDate( $date=FALSE, $long=FALSE, $msg="")
:string
{
$date = $date ?? time();

$result = 'default short date format';

if($long):
  $result = 'long date format';
endif;

$result .= $msg;

return $result;
}//

Edit:
Beware - Typed on a tablet and not tried.

1 Like

I don’t understand it yet :blush: but thanks for taking the time.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.