Ayhan Erdem
Ayhan Erdem

Reputation: 11

I need to use two methods very flexible

First, let me show you my code example:

<?php
    class Example
    {
        public $name;

        public function name(string $name)
        {
            if($name) $this->name = $name;
            else throw new Exception('An argument is required.');

            return $this;
        }

        public function in($name = false, $setting = true)
        {
            if($name) return $this::anotherMethod($name, 'in', $setting);
            elseif($this->name) return $this::anotherMethod($this->name, 'in', $example);
        }
    }

I need to use those methods like:

<?php
    $example = new Example;
    echo $example->name('A Name Here')->in(false);

    // OR / AND

    $example = new Example;
    echo $example::in('A Name Here', false);

So my problem is, I can't use these method both ways because first I don't even know if it's possible to use a method both as static and otherwise, second the arguments of the method called "in" are conflicting. If I try the first example, "false" is gonna take "name" argument's place. I need a way to use these method in both ways, both examples.

Right now, I'm looking at the screen and I'm not able to focus and understand anything, so can anybody please help me? Internet results and my brain isn't helping.

Upvotes: 0

Views: 57

Answers (1)

Umair Khan
Umair Khan

Reputation: 1752

Please try.

class Example
{
    public static $name = '';

    public static function name(string $name)
    {
        if ($name) self::$name = $name;
        else throw new Exception('An argument is required.');

        return new self;
    }

    public static function in($name = false, $setting = true)
    {
        if ($name) {
            self::name($name);
            return self::am($name, 'in', $setting);
        } else {
            return self::am($name, 'out', $setting);
        }
    }

    public static function am($name = false, $dir = 'in', $setting = true)
    {
        var_dump($name, $dir, $setting);
        return $dir;
    }
}
$example = new Example;
echo $example->name('A Name Here')->in(false);

// OR / AND

$example = 'Example';
echo $example::in('A Name Here', false);

Also see Chaining Static Methods in PHP?

Upvotes: 0

Related Questions