Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP Method chaining optional return

At this point, let's say I have a class like so:

class Sentence {
  __construct($content) {
    $this->content = $content;
  }
  public function grab_word($num) {
    $words = explode(" ", $this->content);
    return $words[$num+1];
  }
}

So the interface given would allow me to create a new Sentence, and then I could call the grab_word() class method to fetch a word in the sentence:

$sentence = new Sentence("Lorem ipsum dolor sit amet");
echo $sentence->grab_word(2);

However, what I'd like to do is add another chained class method, giving me the ability to capitalize this word.

$sentence->grab_word(2); # -> ipsum
$sentence->grab_word(2)->caps(); # -> IPSUM

Clearly, this won't work because chained methods require object inheritance. If I were to create caps() and chain that function - it would return an error due to the return not being the inherited Sentence object.

To sum it up, my question is how to I achieve the ability to chain these methods optionally, but still return a non-object whenever needed (like in my output example).

like image 750
Jon McIntosh Avatar asked May 14 '26 18:05

Jon McIntosh


1 Answers

class Sentence {
  function __construct($content) {
    $this->content = $content;
  }
  public function grab_word($num) {
    $words = explode(" ", $this->content);
    return new Sentence($words[$num+1]);
  }
  public function caps() {
    return new Sentence(strtoupper($this->content));
  }
  function __toString(){
      return $this->content;
  }
}

an object with a __toString method isnt totally compatible with a string though. It's still an object, but, it will convert to string when explicitly used in a string context.

like image 154
goat Avatar answered May 17 '26 07:05

goat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!