1

So in this answer to the question: Hidden Features of PHP?

Talks about using standard classes in PHP. Which in his own example looks sweet but I cant get it to work, se here.

The code is:

<?php

$person = new stdClass();
$person->name = 'bob';
$person->age = 5;

$string = "$person->name is $person->age years old.";

?>

I realize I may be completely misinterpreting the answer but anyway, this is what I understood :)

The this I don't understand is (the most important probably) stdClass(); I read: What is stdClass in PHP? but I think I'm even more confused now. (I did't find the accepted answer very useful to be honest)

Thanks in advance!!


EDIT:

Damn!! I'm sorry guys!! I was not code related!! when I copy the code to ideone.com I just copies some other values with it and prevents it from working (or at least this is my best guess) works just fine in codepad.org, I'm switching!!

Community
  • 1
  • 1
Trufa
  • 39,971
  • 43
  • 126
  • 190
  • What's your PHP version? It should work properly. What do you not understand about `stdClass`? – BoltClock Dec 07 '10 at 00:16
  • To put it differently: `stdClass` is the `object` basis type, like in other languages. Albeit in PHP it's not really the basis for all objects. – mario Dec 07 '10 at 00:36

3 Answers3

4

In order to interpolate object members within strings in older versions of PHP, you should surround them with curly braces:

$string = "{$person->name} is {$person->age} years old.";
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • 1
    The braces are not necessary unless you're referring to object properties which are arrays. – BoltClock Dec 07 '10 at 00:13
  • 1
    Thanks @Jacob ! problem solved see my edit, sorry, but it does work without the braces like @alex points out! – Trufa Dec 07 '10 at 00:26
2

Works for me.

Is your PHP > 5.1?

Try this

var_dump(version_compare(PHP_VERSION, 5.1, '>'));

Update

Your example works for me. Did you forget to output your string? :P

alex
  • 479,566
  • 201
  • 878
  • 984
  • No no, I was trying in ideone.com directly, maybe I got something else with the copy paste! let me check, thanks!! – Trufa Dec 07 '10 at 00:17
0

When you use mysql_fetch_object() it returns an instance of stdClass. The columns are the properties of this class. It's like an anonymous class. It's because PHP doesn't have a class for every possible table in the world. So this is very handy.

Stijn Leenknegt
  • 1,317
  • 4
  • 12
  • 22