tags:

views:

42

answers:

2

This is a follow up from yesterday's scope question.

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

Today I want to share the "$template_instance" variable with a child class. How is this accomplished?

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'); 


 }
}
+1  A: 

Make it protected. Protected members will be accessible to the class and its children only.

Visibility Overview

  • Public members: members that are visible to all classes.
  • Private variables: members that are only visible to the class they belong to.
  • Protected variables: members that are only visible to the class in which they belong as well as any of its children (subclasses)
webbiedave
Or make a protected accessor function.
SorcyCat
That too. –––––
webbiedave
A: 

In exactly the same way you were told before

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


   } 
}

or pass your index to the printpage constructor

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

   } 
}
Mark Baker