douyi0219 2015-01-13 03:11
浏览 48
已采纳

创建和访问嵌套对象和函数?

I have a class function that queries data like so:

// Disclaimer: (None of the following is "real")
class Mockup {

  function getData() {

    query("SELECT id,name FROM pages")
    // Results: $id = 1, $name = "Math Text Book: Grade 7"

  }

}

Though I'd like to be able to access both values (That is, $id and $name), I can only return one value individually (Thus creating a disadvantage when compared to simply querying outside of the class).

Would something along the lines of the following be possible in conjunction with the above example code?

$test = new Mockup;
echo $test->getData()->id; // Echos "7"

Similarly, I've seen something along the lines of the following in various software such as MediaWiki:

$test = new Mockup;
echo $test->getData()->getId(); // Echos "7"

Is that an indication that it's also possible to nest functions as well?

  • 写回答

1条回答 默认 最新

  • dpbz14739 2015-01-13 03:45
    关注

    That's not an embedded function it's method chaining. When a method returns the class instance, you can use it to immediately use another class member (var or function), thus chaining them together.

    class Mockup {
    
      public $id;
      public $name;
    
      function getData() {
        $data = query();
        $this->id = $data->id;
        $this->name = $data->name;
        return $this; // return the instance for chaining
      }
    
      function getId() {
        return $this->id;
      }
    
      function getName() {
        return $this->name;
      }
    
    }
    
    $mockup = new Mockup();
    
    //unchained
    $mockup->getData();
    $id = $mockup->getId();
    $name = $mockup->getName();
    // or
    $id = $mockup->id;
    $name = $mockup->name;
    
    //chained
    $id = $mockup->getData()->getId();
    $name = $mockup->getData()->getName();
    //or
    $id = $mockup->getData()->id;
    $name = $mockup->getData()->name;
    

    If you want to return both at once you could simply return an array or an object containing those values.

    FYI: When using chaining you don't have to return the instance of the class you are calling the method from, you can also in that method, create a new instance of another class and return that, so you can call members from that instance, for example:

    $garage->getVehicle('plane')->fly(); // returns new Plane() with specific methods
    $garage->getVehicle('car')->drive(); // returns new Car() with specific methods
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)