donglu9743 2010-07-22 14:24
浏览 29

PHP-与子类共享类变量

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


 }
}
  • 写回答

2条回答 默认 最新

  • douan7601 2010-07-22 14:27
    关注

    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)
    评论

报告相同问题?

悬赏问题

  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图