T
T
TempNickname2014-09-25 18:42:32
PHP
TempNickname, 2014-09-25 18:42:32

How to call a method of one object from another object?

I recently started learning OOP in PHP, and there was a problem in applying knowledge in practice. Let's say I have a MySQL class for connecting to a database, and there is another class, let's call it Page, where a MySQL class method is called.

class MySQL {
public $Vars;

function Connect () {
//code
}
}

class Page {
public $Vars;

function Func () {
$MySQL->Connect();
//code
}
}

$MySQL = new MySQL;
$Page = new Page;

$Page->Func()

I strongly suspect that I did not understand the concept of OOP. How can you call the Connect method of the MySQL class without constantly creating MySQL class objects in every method of the Page class? Or how to implement such a system at all?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Edward, 2014-09-25
@TempNickname

for example, create an object of the MySQL class in the constructor of the Page class and refer to it in all functions

class MySQL
{
    public function connect()
    {
        // code...
    }
}

class Page 
{
    protected $mysql = null;

    public function __constuct()
    {
        $this->mysql = new MySQL;
    }

    public function view($id)
    {
        $this->mysql->where($id);
    }

    public function delete($id)
    {
        $this->mysql->delete($id);
    }
}

$page = new Page;
$page->view($id);
$page->delete($id);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question