dongshendie8849 2012-09-22 03:48
浏览 34
已采纳

理解面向对象的PHP有点帮助[重复]

Possible Duplicate:
PHP method chaining?

I'm relatively new to PHP and OOP, and I'm having trouble understanding a recurring structure popping up in my database code.

I understand how to create a class, instantiate it, as well as access properties and methods, but $myobject->function() is about as complicated as it gets for me for now.

What is this structure?

$myobject->function()->something. I am repeatedly seeing this more and more, especially as I start wrapping my head around mysql PDO queries. For example:

$query->function1($arg)
  ->function2($arg)
  ->function3($arg);

What's happening here? is it simply chaining one call of multiple methods in the class, or are those sub functions of function1()? What would the class definition look like?

  • 写回答

6条回答 默认 最新

  • dream0776 2012-09-22 03:55
    关注

    $myobject->function() is returning an object, ->something would access a field on that object.

    Basically, the main concept in this programming method is that an object contains data and methods (or "functions") to interact with the contained data. These containers can be conveniently passed around. PHP is giving you some shorthand so you don't have to assign everything to a variable.

    Returning objects is a way to layer functionality, so your PDO object, which has a query method, may return a row object. The row object has its own set of methods (e.g. for getting column values), so you can then invoke those methods.

    So:

    $pdo->queryOneRow(...)->getValue(<some column>)
    

    Is really just shorthand for:

    $result = $pdo->queryOneRow(...);
    $result->getValue(<some column>)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染