What does the syntax '%s' and '%d'

2020-04-09 20:30发布

问题:

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?

回答1:

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.



回答2:

That's part of the printf method. Those are placeholders for the variables that follow. %d means treat it as a number. %s means treat it as a string.

The list of variables that follow in the function call are used in the order they show up in the preceding string.



回答3:

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

%d means format as "integer", and is being replaced by the value in$this->color

printf is a "classic" function that have been around for a while and are implemented in many programming languages.

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



标签: php oop