What does the syntax ā€œ% sā€ and ā€œ% dā€ mean as a shorthand for calling a variable?

What do ā€œ% sā€ and ā€œ% dā€ mean in this example? This seems to be a shorthand for calling variables. Does this syntax only work in 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 bothers me how the compiler knows which variable% d refers to? Is this done only in the order in which the member variables are declared?

+4
source share
3 answers

They are format specifiers, that is, a variable of the specified type will be inserted into the output at this position. This syntax also works outside of classes.

From the documentation:

d - the argument is treated as an integer and is represented as a (signed) decimal number.

s - the argument is considered as represented as a string.

See the manual on printf . For a list of format specifiers, see here .

+8
source

This part of the printf method. These are placeholders for the variables that follow. % d means treating it as a number. % s means treating it as a string.

The list of variables that follow in the function call is used in the order in which they appear on the previous line.

+1
source

%s means format as "string" and is replaced by the value in $this->number_of_floors

%d means format as an "integer" and is replaced by a value in $this->color

printf is a "classic" function that has existed for some time and has been implemented in many programming languages.

http://en.wikipedia.org/wiki/Printf

+1
source

All Articles