如何调用类方法?

时间:2015-06-01 19:08:45

标签: php class oop methods

当我尝试使用private function sqlConnection(){

时,我的代码出现问题

我有这段代码:

<?php
require "transferDao/daoTransferProyectos.php";
class daoProyectos{
private function sqlConnection(){

        try {

            $servername = "localhost"; 
            $username = "root";
            $password = "123asd";
            $conn = new PDO("mysql:host=$servername;dbname=bd_actividades", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  

        }
        catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
    }   
 public function resultSelect(){

            $aObjects=array();

            $db = sqlConnection();
            $stmt = $db->prepare("SELECT pro_id, pro_nombre FROM act_proyecto");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $result = $stmt->fetchAll();

            foreach ($result as $row) {
            $aTransfer = new daoTransferProyectos();
            $aTransfer->setId($row['pro_id']);
            $aTransfer->setNombreProyecto($row['pro_nombre']);
            $aObjects[]=$aTransfer;
            }
            return $aObjects;
    }
}
?>

我有这个错误:

  

[Mon Jun 01 21:56:00.569136 2015] [:error] [pid 7015] [client 10.0.2.2:61625] PHP致命错误:在/ var / www / html / PROJECTS中调用未定义的函数sqlConnection()第28行的/dailytasks/dao/daoProyectos.php,引用者:http://localhost:8080/formulario_web/formulario/formulario_lazos.html

如何解决此错误?

修改

如果我使用:

$db = $this->sqlConnection();

然后我收到一个新错误:

  

[Mon Jun 01 22:11:00.530604 2015] [:error] [pid 7015] [client 10.0.2.2:61957] PHP致命错误:在/ var中的非对象上调用成员函数prepare()第29行/www/html/PROJECTS/dailytasks/dao/daoProyectos.php,引用者:http://localhost:8080/formulario_web/formulario/formulario_lazos.html

2 个答案:

答案 0 :(得分:4)

此:

$db = sqlConnection();

应该是:

$db = $this->sqlConnection();
    //^^^^^^^ See here

换句话说,您试图调用一个不存在的全局函数,而不是您的对象方法。 e.g。

function foo() {
   echo 'global function foo';
}

class bar() {
   function foo() {
      echo 'method foo';
   }
   function bar() {
      foo();        // prints: global function foo
      $this->foo(); // prints: method foo
   }
}

答案 1 :(得分:0)

添加:

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
return $conn;  <-- add this line