【问题标题】:Using SQL function from SQL handling class in other functions在其他函数中使用 SQL 处理类中的 SQL 函数
【发布时间】:2012-06-12 08:07:00
【问题描述】:

我在一个名为 SQLHandling 的类中创建了一个 SQL 函数 SQLquery 它看起来像这样:

 /***********************************************************
    * SQLquery takes a full SQL query and runs it
    * If it fails it will return an error otherwise it will return
    * the SQL query as given.
    ************************************************************/   
    function SQLquery($query)  { 

        $q = mysql_query($query);

        if(!$q) {
            die(mysql_error());
            return false;
        } else {
            return $q;          
        }
    }

反正我可以在其他类函数中使用这个函数而不添加

$db = new SQLHandling();
$db->SQLquery($sql);

在我将使用它的每个功能中。

我知道我可以运行SQLHandling::SQLquery($sql);,但我正在努力避免这种情况。

【问题讨论】:

    标签: php sql class function


    【解决方案1】:

    使用继承

    参考: http://php.net/manual/en/language.oop5.inheritance.php

    但您仍然需要使用 parent::fun() 或 $this->fun() 或者把它作为一个公共函数然后在任何地方使用。

    示例:

    <?php
    
    function c()
    {
            echo "moi";
    }    
    
    class b extends a
    {       
       public function d(){
    
        parent::c();//Hai
        $this->c();//Hai
        c();//moi
    
        }   
    
    
    }
    
    
    class a{    
    
    
    
        public function c(){
            echo "Hai";
    
        }       
    } 
    
    
    $kk = new b();
    $kk -> d();
    
    ?>
    

    【讨论】:

    • 您是在建议他应该在其他类中扩展 SQLHandling?我认为没有任何理由这样做..
    【解决方案2】:

    您可以在类级别实例化 SQLHandling,如下所示:

        private $db;
    
        public function __construct()
        {
            $this->db = new SQLHandling();
        }
    
        public function x()
        {
            $this->db->query('X');
        }
    

    【讨论】:

    • 这正是我想要的!发现!非常感谢你! :)
    猜你喜欢
    • 1970-01-01
    • 2011-06-08
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    相关资源
    最近更新 更多