-1

I've been tinkering with PHP to learn a few new things (hopefully) and I was wondering, is there any advantages/disadvantages to using classes like these in the place of strings:

class Str
{
    protected $value = "";

    public function __construct($string)
    {
        if (is_string($string)) {
            $this->value = $string;
            return true;
        } else {
            return false;
        }
    }

    public function contains($needle)
    {
        return strpos($this->value, $needle) !== false;
    }

    public function startsWith($needle)
    {
        return substr($this->value, 0, strlen($needle)) === $needle;
    }

    public function endsWith($needle)
    {
        return substr($this->value, -strlen($needle)) === $needle;
    }

    public function value()
    {
        return $this->value;
    }
}
Prinsig
  • 245
  • 3
  • 9
  • 1
    Sidenote: `constructors` can't return a value. Their only purpose is to initiate the class – DarkBee Jan 08 '15 at 11:25
  • It is totally based on your design. – vaso123 Jan 08 '15 at 11:25
  • This is the same as asking if you'll find orange juice tasty. How the hell can anyone know besides you, who uses this thing? If you find it useful, then it's useful. If you don't find it useful, then it's not useful. It's *as simple as that*. Don't try to please imaginary code god, just focus on your task and do it in the simplest and cleanest way possible. – N.B. Jan 08 '15 at 11:28
  • Updates the question to include the phase "in the place of strings". – Prinsig Jan 08 '15 at 11:30
  • Note that PHP has already provided an option for scalar-type class like this as part of [SPL Types](http://www.php.net/manual/en/book.spl-types.php), and while these don't have methods for all the relevant functions such as contains/strpos, etc, they can provide a basic framework if you want to build your own – Mark Baker Jan 08 '15 at 11:50

2 Answers2

1

This is more testable than static method calls. Besides that, there is no problem in doing something like that and no advantage/disadvantage is clearly visible. In fact, there is a utility package that does exactly what you're doing. Take a look at Stringy.

Waldson Patricio
  • 1,489
  • 13
  • 17
0

Well, just by seeing this class we cannot tell you if it's usefull or not. I can tell you that Object Oriented Programming is better than procedural programming.

If you want to find out why this is, I suggest reading this question and answers.

Community
  • 1
  • 1
Peter
  • 8,776
  • 6
  • 62
  • 95