developerto_jrm
developerto_jrm

Reputation: 60

PHP does not recognize method defined in class

I get the following error:

Fatal error: Call to undefined method database::connect() in
/Applications/XAMPP/xamppfiles/htdocs/proyectoFinal/core/class.ManageDatabase.php 
on line 8

Does anyone know what is going on? The method IS defined inside the class. This part seems to be the problem : $this->link = $conn->connect();

Class is as follows:

<?php 

include_once('../config.php');

    class database{
        protected $db_conn;
        public $db_name = DB_NAME;
        public $db_host = DB_HOST;
        public $db_pass = DB_PASS;
        public $db_user = DB_USER;  
    }

    function connect(){
        try{
            $this->$db_conn = new PDO("mysql:host = 
                    $this->db_host;dbname=$this->db_name",
                    $this->db_user, $this->db_pass);
            return $this->db_conn;  
        }
        catch(PDOException $e)
        {
        return $e->getMessage();
        }
    }
?>

Methods called by the following:

<?php
    include_once('../core/class.ManageDatabase.php');
    $init = new ManageDatabase;

    $table_name = 'persona';
    $data = $init->getData($table_name);

    print_r($data);
?>

Upvotes: 0

Views: 806

Answers (2)

Daryl Gill
Daryl Gill

Reputation: 5524

You have closed off your class, so: function connect(){ /* */ }

is out of Object Scope.

class database{
        protected $db_conn;
        public $db_name = DB_NAME;
        public $db_host = DB_HOST;
        public $db_pass = DB_PASS;
        public $db_user = DB_USER;  
    } // Remove this and add it at the end of your class definition 

That being said, database->connect(); will not be a defined method.. Rather:

$Var = connect();

which will work with the current setup

Upvotes: 0

Havenard
Havenard

Reputation: 27864

class database{
    protected $db_conn;
    public $db_name = DB_NAME;
    public $db_host = DB_HOST;
    public $db_pass = DB_PASS;
    public $db_user = DB_USER;  
} // <-- end of class database

It doesn't have any methods indeed. I believe you should move this } if you want the function connect() to become one of its methods, and place it only after the function.

Upvotes: 1

Related Questions