PHP-与子类共享类变量

时间:2010-07-22 14:24:53

标签: php oop class

这是昨天范围问题的后续跟进。

stackoverflow.com/questions/3301377/class-scope-question-in-php

今天我想与子类共享“$ template_instance”变量。 这是如何完成的?

require_once("/classes/Conf.php");
require_once("/classes/Application.php");

class index extends Application
{
    private $template_instance;

    // Dependency injection
    public function __construct(Smarty $template_instance)
    {
        $this->template_instance = $template_instance;
    }

    function ShowPage()
    {
        // now let us try to move this to another class 
        // $this->template_instance->assign('name', 'Ned'); 
        // $this->template_instance->display('index.tpl'); 

    }   
}

$template_instance = new Smarty();
$index_instance = new Index($template_instance);
//$index_instance->showPage();

$printpage_instance = new printpage();
$printpage_instance->printSomething();


------------------------------------------------------------------

class printpage
{ 
 public function __construct()
 {


 }

 public function printSomething()
 {    

        // now let us try to move this to another class 
         $this->template_instance->assign('name', 'Ned'); 
         $this->template_instance->display('index.tpl'); 


 }
}

2 个答案:

答案 0 :(得分:1)

制作protected。受保护的成员只能访问该类及其子级。

可见性概述

  • 公众成员:成员 所有课程都可以看到。
  • 私有变量:成员 只有班上可见 他们属于。
  • 受保护的变量:成员 只有班级可见 它们属于哪个子类(子类)

答案 1 :(得分:0)

与之前被告知的方式完全相同

$printpage_instance = new printpage($template_instance); 
$printpage_instance->printSomething(); 


------------------------------------------------------------------ 

class printpage 
{  

   private $template_instance;    

   public function __construct(Smarty $template_instance) 
   { 


      $this->template_instance = $template_instance;   
   } 

   public function printSomething() 
   {     

        // now let us try to move this to another class  
         $this->template_instance->assign('name', 'Ned');  
         $this->template_instance->display('index.tpl');  


   } 
}

或将索引传递给printpage构造函数

$printpage_instance = new printpage($template_instance); 
$printpage_instance->printSomething(); 


------------------------------------------------------------------ 

class printpage 
{  

   private $index;    

   public function __construct(index $index) 
   { 


      $this->index = $index;   
   } 

   public function printSomething() 
   {     

         $this->index->ShowPage(); 

   } 
}