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

报告相同问题?

悬赏问题

  • ¥20 关于php中URL传递GET全局变量的问题
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件