drxv39706
2012-07-25 14:26
浏览 105
已采纳

PHP / OOP - 在类中初始化类

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

图片转代码服务由CSDN问答提供 功能建议

我是OOP的新手,但不是PHP的新手。 我正在尝试从另一个类中初始化一个类。

的index.php

 <代码>&LT;?
error_reporting(E_ALL); 
require( “类/ memcache.php”); \  nrequire(“classes / video_test.php”); 
 $ videos = new video; 
?&gt; 
   
 
 

video_test.php

 &lt;?php 
 class video {
 
 private $ mcache; 
 
 public function __construct(){
 $ this-&gt; mcache = new MCACHE(); \  n} 
 
公共静态函数get_scene($ scene_id){
 $ info = $ this-&gt; $ mcache-&gt; get_item(“mykey”); 
} 
 
 
} 
?  &gt; 
   
 
 

生成: PHP致命错误:在 中不在对象上下文中时使用$ this

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongshi9489 2012-07-25 14:27
    已采纳

    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();
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doucong3048 2012-07-25 14:37

    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)

    评论
    解决 无用
    打赏 举报
  • dongshi1102 2012-07-27 19:10

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题