Why is $this not the correct type of object?

215 Views Asked by At

I'm trying to implement a simple PHP db framework (Medoo) into PHPLib, but am stuck on the following:

I have this structure

index.php which initiates

  • new medoo object
  • new application object

the application class handles general settings for each app, and extends from my medoo class.

Each app has its own class (e.g. Foo) , and an foo/app.php file. the foo class extends from the application class. the foo/app.php file generates the view, and in this file a foo object is created.

But it's in the Foo class i'm trying to connect with my database with the medoo class. The medoo class has some protected properties which are accessible within the Foo class (e.g. $this->medoo_property)

but whenever i'm trying to run use a method from the medoo class i'm getting stuck at this error: Fatal error: Call to a member function something() on a non-object in something

when I do a var_dump of $this right before the error in the medoo class, it says it is an Foo object instead of a Medoo object. So it's obvious it throws an error of non-object, because it tries to use a medoo property in a Foo object.

I have the same error implementing another php (PDO) class, so the error is on my side, but I can't figure out what it is I'm doing wrong. I hope my problem is explained properly, feel free to ask more info if needed.

Any help much appreciated.

2

There are 2 best solutions below

2
On

I think, from your code and description given, that your facing a scoping problem.

If your calling $this in the Foo class, you're not going back to the Medoo (Parent) Class, $this refers in this case to the direct instance of Foo. So you're calling a function that's not given. As you said already.

What you need is the Parent function from PHP, so you can call the functions from Medoo in Foo.

As simple example taken from the official documentation:

<?php
class A {
    function example() {
        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>

Also you should not set all properties to public, it's bad practice and bad scoping. You should set them to private if no child of this class should be able to easily access them or protected if childs should access and manipulate them.

To further gurantee the accessabilty to this properties you need getter and setters.

0
On

fixed it by replacing this with self in the medoo class, and making the properties static