Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the syntax '%s' and '%d' mean as shorthand for calling a variable?

Tags:

oop

php

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?

like image 733
user784637 Avatar asked Jul 28 '11 21:07

user784637


People also ask

What does %s mean in PHP?

%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.

What is %d %s in C?

%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].


1 Answers

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.

like image 78
barfoon Avatar answered Sep 24 '22 19:09

barfoon