Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a natural String class in PHP

Tags:

string

oop

php

Hai. I was making this simple string class and was wondering if there was a more natural way of doing it.

class Str{
    function __construct($str){
        $this->value = $str;
        $this->length = strlen($str);
        ..
    }

    function __toString(){
        return $this->value;
    }
    ..
}

so now i have to use it like this:

$str = new Str('hello kitty');
echo $str;

But that doesnt look very 'natural' with the parentheses. So i was wondering if something like this, or similar was possible.

$str = new Str 'hello kitty'; # I dont believe this is possible although this is preferred.

$str = new Str; # get rid of the construct param.
$str = 'value here'; #instead of resetting, set 'value here' to Str::$value??

In the second method, is there a way i could possibly catch that variable bing set again and instead of reseting it, set this to Str::$value ? I have thought around and the closest i could come up to is the __destruct method. but there was no possible way to know how it was being destroyed. Is this possible or am i wasting my time?

like image 794
shxfee Avatar asked Mar 06 '10 07:03

shxfee


3 Answers

Since PHP is loosely typed, there is no natural string class, because the natural way of using strings is, well, by just using them. However, as of PHP5.3 there is an extension in the SPL that provides strongly typed scalars:

  • http://php.net/manual/en/book.spl-types.php

However, keep in mind that this extension is marked experimental and subject to change. As of now, it is also not available on Windows.

You might also want to try https://github.com/nikic/scalar_objects

This extension implements the ability to register a class that handles the method calls to a certain primitive type (string, array, ...). As such it allows implementing APIs like $str->length().

like image 128
Gordon Avatar answered Oct 02 '22 19:10

Gordon


Also See: https://github.com/alecgorge/PHP-String-Class

A good string class

like image 27
Handsome Nerd Avatar answered Oct 02 '22 18:10

Handsome Nerd


  1. It's impossible to call functions in PHP without parentheses.
  2. Your next method will change the reference to string.

Why it doesn't look natural to you? It's the same way in Java.

You may find this useful:

php-string

like image 21
Sagi Avatar answered Oct 02 '22 19:10

Sagi