php 语法“%s”和“%d”作为调用变量的简写是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6865673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does the syntax '%s' and '%d' mean as shorthand for calling a variable?
提问by user784637
What do '%s' and '%d' mean in this example? It appears its shorthand for calling variables. Does this syntax only work within a class?
'%s' 和 '%d' 在这个例子中是什么意思?它似乎是调用变量的简写。此语法仅在类中有效吗?
// 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?
编辑:让我困惑的部分是编译器如何知道 %d 指的是哪个变量?它是否只是按照成员变量的声明顺序进行的?
回答by barfoon
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.
d - 参数被视为整数,并表示为(有符号)十进制数。
s - 参数被视为并显示为字符串。
See the manual on printf. For a list of format specifiers, see here.
回答by Zack Marrapese
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.
这是 printf 方法的一部分。这些是后面变量的占位符。%d 表示将其视为数字。%s 表示将其视为字符串。
The list of variables that follow in the function call are used in the order they show up in the preceding string.
函数调用中的变量列表按照它们在前面字符串中出现的顺序使用。
回答by JK.
%s
means format as "string" and is replaced by the value in$this->number_of_floors
%s
表示格式为“字符串”并由中的值替换$this->number_of_floors
%d
means format as "integer", and is being replaced by the value in$this->color
%d
表示格式为“整数”,并被替换为中的值$this->color
printf is a "classic" function that have been around for a while and are implemented in many programming languages.
printf 是一个“经典”函数,它已经存在了一段时间,并在许多编程语言中实现。