What do '%s' and '%d' mean in this example? It appears its shorthand for calling variables. Does this syntax only work within a class?
// Class
class Building {
// Object variables/properties
private $number_of_floors = 5; // These buildings have 5 floors
private $color;
// Class constructor
public function __construct($paint) {
$this->color = $paint;
}
public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}
EDIT: The part that is confusing to me is how does the compiler know which variable %d is referring to? Does it just go in the order that the member variables were declared?
%s is a type specifier which will be replaced to valuable's value (string) in case of %s . Besides %s you can use other specifiers, most popular are below: d - the argument is treated as an integer, and presented as a (signed) decimal number.
%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].
They are format specifiers, meaning a variable of a specified type will be inserted into the output at that position. This syntax works outside of classes as well.
From the documentation:
d - the argument is treated as an integer, and presented as a (signed) decimal number.
s - the argument is treated as and presented as a string.
See the manual on printf. For a list of format specifiers, see here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With