-1

All,

I'm a fairly new and I mostly studied OOP with Java.

With this said, here is the relevant code:

Model.php

class Model{ // Object that represents a connection to the relevant db table
        private $db; //contains the identifiers of the db
        private $dao;

        function createRecord1(){
            return $this->dao->createRecord();
        }
    }

User_Model.php

class Model_user extends Model {
        function __construct($db){
            $this->db=$db;
            $dao=DAO_DBrecord::createUserDAO($this->db);//  This is a static function that calls the DAO constructor with a 'user' table name parameter
            $this->dao=$dao;
        }
    }

Then in Controller_Register.php, I have this code:

//Some other code
$db=DB::createDB();
$userModel=new Model_User($db);
$userID=$userModel->createRecord1();
//Some more code

This yields the error message I have in the title. The line return $this->dao->createRecord(); inside Model.php causes the error.

There is no error if the function createRecord1() is placed in Model_User instead of in the parent class - but then of course I would have to duplicate it in other children.

What am I doing wrong?

JDelage
  • 13,036
  • 23
  • 78
  • 112
  • 1
    While I'm not certain if it's the cause of your errors, be aware that in PHP, private members are *not* accessible in descendant classes. – Charles Feb 13 '12 at 23:16

2 Answers2

2

The "same" code in Java would result in the same errors. $db and $dao are specified as private class members of Model, so are not available for you to manipulate directly in classes which extend Model. Try changing

class Model {
        private $db;
        private $dao;
        ...

to

class Model {
        protected $db;
        protected $dao;
        ...

You can read more about this in the PHP documentation:

Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Gordon
  • 312,688
  • 75
  • 539
  • 559
thetaiko
  • 7,816
  • 2
  • 33
  • 49
2

You don't want $dao and $db to be private. If they are private, the subclass does not share access with the parent.

You want them to be protected.

Borealid
  • 95,191
  • 9
  • 106
  • 122