Seeing other languages like Java or C++, String is an Object.
But in PHP is it the same thing?
-
PHP supports OOP, but is not fundamentally oop-based. strings are not objects in PHP.Marc B– Marc B2013-03-28 16:11:59 +00:00Commented Mar 28, 2013 at 16:11
-
You can actually have a string object in PHP with the SPL Types: php.net/manual/en/class.splstring.php ... but this is very new and very buggyMark Baker– Mark Baker2013-03-28 16:23:47 +00:00Commented Mar 28, 2013 at 16:23
-
It's not natively an object but you could create your own string class if you wished. Just a few days ago I was thinking about this.EM-Creations– EM-Creations2013-03-28 16:30:53 +00:00Commented Mar 28, 2013 at 16:30
-
Is it the literal "String"? Or just a string?Peter Mortensen– Peter Mortensen2023-11-14 15:07:38 +00:00Commented Nov 14, 2023 at 15:07
6 Answers
A String is not an object in PHP by default and casting is not required but it can be introduced if you want using scalar_objects
class StringHandler {
public function length() {
return strlen($this);
}
}
register_primitive_type_handler('string', 'StringHandler');
So you can easily have
$str->length();
Comments
A string is not an Object in PHP. You don't have to cast the types of variables in PHP. See
http://www.php.net/manual/language.types.string.php
and http://php.net/manual/language.types.type-juggling.php
4 Comments
$name = "John"; makes a String. PHP is much simpler than C(++) in this case. It tries to figure out what type your suggest.$name = (string)"John"; or $number = (int)"99";String and object are two different things. But if you wanted to run your own checks:
if (is_object($var))
{
echo "Var is an object";
}
elseif (is_string($var))
{
echo "var is a String";
}
else
{
echo "var is neither an object or string";
}
3 Comments
String is not an object in PHP; it's a primitive type. The information is on Types.
A lowercase string is correct for the few uses you might have.