简体   繁体   English

我需要使用两种非常灵活的方法

[英]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.所以我的问题是,我不能同时使用这些方法,因为首先我什至不知道是否可以同时使用 static 和其他方法,其次调用“in”的方法的 arguments 是冲突的。 If I try the first example, "false" is gonna take "name" argument's place.如果我尝试第一个示例,“false”将取代“name”参数。 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?现在,我正在看着屏幕,但我无法集中注意力并理解任何内容,所以有人可以帮助我吗? Inte.net results and my brain isn't helping. Inte.net 结果和我的大脑没有帮助。

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?另请参阅PHP 中的链接 Static 方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM