Joe O
Joe O

Reputation: 79

PHP / OOP - initializing class within a class

I am fairly new to OOP but not new to PHP. I am trying to initialize a class from within another class.

index.php

<?
error_reporting(E_ALL);
require("classes/memcache.php");
require("classes/video_test.php");
$videos = new video;
?>

video_test.php

<?php
    class video {

            private $mcache;

            public function __construct() {
            $this->mcache = new MCACHE();
            }

            public static function get_scene($scene_id) {
            $info = $this->$mcache->get_item("mykey");
            }


    }
?>

Produces: PHP Fatal error: Using $this when not in object context in

Upvotes: 1

Views: 164

Answers (3)

bryan.blackbee
bryan.blackbee

Reputation: 1954

Just to add on, there are key differences between a class and an instance. when we say a static method or attribute belongs to a class, it means all instances of the class share this one attribute. In contrast, an object instance has its own set of individual attributes. To master OOP, this understanding is pretty important.

Upvotes: -1

karka91
karka91

Reputation: 733

Static methods belong to the class and not the object which you create with new. $this pseudovariable refers to the object and not the class. This is why your code breaks. You can fix this piece of code simply by removing the static keyword before the function. Or you could redefine the whole thing statically (you would use self:: instead of $this, declare the $mcache static and create a static method to initialise that variable)

Another bug that you made is: $this->$mcache. To properly access properties you write $this->mcache. Your code was trying to access a property named with what is in $mcache variable that wasn't defined in the function (thus you were trying to access $this->null)

Upvotes: 1

Alex Howansky
Alex Howansky

Reputation: 53563

Using $this when not in object context in

You can't use $this in a method that's declared static. Just remove the static keyword and use your method via the object handle:

$vid = new video()
$vid->get_scene();

Upvotes: 7

Related Questions