dongzhao1930 2012-11-13 10:53
浏览 48

在另一个类中的类

I am new to PHP OOP and would like to try to nest several classes within another class, to latter call them like so:

$sql = new SQL();
$sql->Head()->Description($_SESSION['page']);
  //OR
$sql->Head()->Keywords($_SESSION['page'])
  //OR
$sql->Body()->Clients($_SESSION['client'])
  //ETC
$query = $sql->Run(); // equivalent to mysql_query("...");

As you can guess, I run into some problems and ended with this poor code:

<?php
require( $_SERVER['DOCUMENT_ROOT'] . '/#some_db_directory/database.php');
//This file contains $db['host'], $db['user'], etc...

class SQL {
    public $sql;

    public function __construct() {
        global $db;
    }

    public class Head() {

        public function Description($page) {
            return "SELECT * FROM `$db['database']`.`desciption` WHERE `page` = '$page'";
        }

        public function Keywords($page) {
            return "SELECT * FROM `$db['database']`.`keywords` WHERE `page` = '$page'";
        }
    }
}

$sql = new SQL();
echo $sql->Head()->Description('home'); //For testing
  • Is it possible to nest classes in PHP?
  • If so, how is it done?
  • 写回答

3条回答 默认 最新

  • dongyaofu0599 2012-11-13 11:00
    关注

    Try it like this

    <?php
    require( $_SERVER['DOCUMENT_ROOT'] . '/#some_db_directory/database.php');
    //This file contains $db['host'], $db['user'], etc...
    
    class SQL {
        public $sql;
        private $_head;
    
        public function __construct() {
            global $db;
            $_head = new HeadClass();
        }
    
        public function Head() {
            return $this->_head;
        }
    }
    
    class HeadClass { // Class cannot have a public access modifier
    
        public function Description($page) {
            return "SELECT * FROM `" . $db['database'] . "`.`desciption` WHERE page = $page";
        }
    
        public function Keywords($page) {
            return "SELECT * FROM `" . $db['database'] . "`.`keywords` WHERE page = $page";
        }
    }
    
    $sql = new SQL();
    echo $sql->Head()->Description('home.html');
    ?>
    

    I am moving the class declaration outside the class and creating an instance of the class with in SQL. This is then made available via the Head() function.

    Note: For body you will need to create a separate class and use a reference in the SQL class to it like I have done for head.

    评论

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答