PHP-与子类共享类变量

PHP-与子类共享类变量,php,oop,class,Php,Oop,Class,这是昨天范围问题的后续内容 stackoverflow.com/questions/3301377/class-scope-question-in-php 今天我想与一个子类共享“$template\u instance”变量。 这是如何实现的 require_once("/classes/Conf.php"); require_once("/classes/Application.php"); class index extends Application { private $te

这是昨天范围问题的后续内容

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

今天我想与一个子类共享“$template\u 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'); 


 }
}
成功了。受保护的成员仅可供类及其子类访问

可见性概述
  • 公共成员: 对所有类都可见
  • 私有变量:成员 仅对类可见 他们属于我
  • 受保护变量:成员 仅对类可见的 它们所属的任何子类(子类)

以与之前完全相同的方式告诉您

$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(); 

   } 
}

或者创建一个受保护的访问器函数。