php学习笔记之面向对象编程

一个php初学者的一个学习笔记的面向对象编程实例,有需要学习的朋友可参考参考.

PHP实例代码如下:

  1. class db {
  2. private $mysqli; //数据库连接
  3. private $options; //SQL选项
  4. private $tableName; //表名
  5. public function __construct($tabName) {
  6. $this->tableName = $tabName;
  7. $this->db ();
  8. }
  9. private function db() {
  10. $this->mysqli = new mysqli ( 'localhost', 'root', '', 'hdcms' );
  11. $this->mysqli->query("SET NAMES GBK");
  12. }
  13. public function fields($fildsArr) {
  14. if (emptyempty ( $fildsArr )) {
  15. $this->options ['fields'] = '';
  16. }
  17. if (is_array ( $fildsArr )) {
  18. $this->options ['fields'] = implode ( ',', $fildsArr );
  19. } else {
  20. $this->options ['fields'] = $fildsArr;
  21. }
  22. return $this;
  23. }
  24. public function order($str) {
  25. $this->options ['order'] = "ORDER BY " . $str;
  26. return $this;
  27. }
  28. public function select() {
  29. $sql = "SELECT {$this->options['fields']} FROM {$this->tableName} {$this->options['order']}";
  30. return $this->query ( $sql );
  31. }
  32. private function query($sql) {
  33. $result = $this->mysqli
  34. ->query ( $sql );
  35. $rows = array ();
  36. while ( $row = $result->fetch_assoc () ) {
  37. $rows [] = $row;
  38. }
  39. return $rows;
  40. }
  41. private function close() {
  42. $this->mysqli
  43. ->close ();
  44. }
  45. function __destruct() {
  46. $this->close ();
  47. }
  48. }
  49. $chanel = new db ( "hdw_channel" );
  50. $chanelInfo = $chanel->fields ( 'id,cname,cpath' )
  51. ->select ();
  52. echo "<pre>";
  53. print_r ( $chanelInfo );
  54. class a {
  55. protected function aa(){
  56. echo 222;
  57. }
  58. }
  59. class b extends a{
  60. function bb(){
  61. $this->aa();
  62. }
  63. }
  64. $c = new b();
  65. $c->bb();

public 公有的:本类,子类,外部对象都可以调用.

protected 受保护的:本类 子类,可以执行,外部对象不可以调用.

private 私有的:只能本类执行,子类与外部对象都不可调用.