面向对象 (OO) 是“事后”附加到 PHP 上的东西。在实现 OO 之前,一切都是使用函数完成的(就像许多其他类似 C 的编程语言一样)。
对于 PHP,字符串、整数、布尔值等只是数据。它们是原始类型,不能做任何事情;它们只是存储在内存中的命名值。这就是为什么您需要使用函数,例如strlen($str)
. 该函数对 value 进行操作。
In languages like Ruby and Javascript most data types, such as strings, are, practically speaking, actually objects (or in some cases kinda-sorta objects). They contain various properties like .length
, and methods like .indexOf()
. Another word for such data types is a composite type (they are composed of more than one thing).
So, in PHP you can say that it is normal to write strlen($str)
to figure out how long a string is; likewise, in Javascript or Ruby it is normal to write str.length
.
It is possible to write a String
class in PHP, but it is kind of beside the point. It is like learning to count to ten, but insisting that it be done in base-7. It is not very practical, and people will think you are crazy.