【问题标题】:I need to use two methods very flexible我需要非常灵活地使用两种方法
【发布时间】:2020-09-30 00:21:23
【问题描述】:

首先,让我向您展示我的代码示例:

<?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);
        }
    }

我需要使用以下方法:

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

    // OR / AND

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

所以我的问题是,我不能同时使用这些方法,因为首先我什至不知道是否可以将方法同时用作静态方法和其他方法,其次称为“in”的方法的参数是冲突的.如果我尝试第一个示例,“false”将取代“name”参数。我需要一种方法以两种方式使用这些方法,两个示例。

现在,我正在看屏幕,无法集中注意力和理解任何内容,有谁能帮帮我吗?互联网结果和我的大脑没有帮助。

【问题讨论】:

    标签: php class methods flexibility


    【解决方案1】:

    请尝试。

    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);
    

    另见Chaining Static Methods in PHP?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-28
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      相关资源
      最近更新 更多