代码之家  ›  专栏  ›  技术社区  ›  ParisNakitaKejser

如何在PHP5中构建多oop函数

  •  2
  • ParisNakitaKejser  · 技术社区  · 15 年前

    我有一个关于PHP5中OOP的问题。我看到越来越多的代码是这样写的:

    $object->function()->first(array('str','str','str'))->second(array(1,2,3,4,5));
    

    但我不知道如何创建这个方法。我希望有人能帮我,:0)非常感谢。

    2 回复  |  直到 14 年前
        1
  •  8
  •   cHao    15 年前

    在您自己的类中链接方法的关键是返回一个对象(几乎总是 $this ),然后用作下一个方法调用的对象。

    像这样:

    class example
    {
        public function a_function()
        {
             return $this;
        }
    
        public function first($some_array)
        {
             // do some stuff with $some_array, then...
             return $this;
        }
        public function second($some_other_array)
        {
             // do some stuff
             return $this;
        }
    }
    
    $obj = new example();
    $obj->a_function()->first(array('str', 'str', 'str'))->second(array(1, 2, 3, 4, 5));
    

    注意,可以返回 $这个 ,上面的链接只是一个简短的说法 $a = $obj->first(...); $b = $a->second(...); ,减去设置变量的丑陋,在调用之后您将永远不会再使用这些变量。

        2
  •  0
  •   MrWhite    15 年前
    $object->function()->first(array('str','str','str'))->secound(array(1,2,3,4,5));
    

    first() second() .

    可能不同 班级。

    比如:

    class AnotherClass {
        public function AnotherClassMethod() {
            return 'Hello World';
        }
    }
    
    class MyClass {
        public function MyClassMethod() {
            return new AnotherClass();
        }
    }
    
    $object = new MyClass();
    echo $object->MyClassMethod()->AnotherClassMethod();  // Hello World
    
    推荐文章