LoginSignup
3
3

More than 5 years have passed since last update.

protectedへのアクセスが出来る?

Last updated at Posted at 2014-09-24

Smartyの勉強を始めたところ、よく分からないことで躓いた。

BaseSmartyは共通設定と関数のオーバーライド、そしてdata変数の定義。
FormではBaseSmartyの継承とフォーム用のデータのセット、そしてメソッド呼び出し。

BaseSmarty.php
require_once('Smarty-3.1.19/libs/Smarty.class.php');

class BaseSmarty extends Smarty
{
    protected $data;

    public function __construct()
    {
        parent::__construct();

        $this->template_dir = 'templates/';
        $this->compile_dir  = 'templates_c/';
        $this->config_dir   = 'configs/';
        $this->cache_dir    = 'cache/';
    }

    protected function display($template = null, $cache_id = null, $compile_id = null, $parent = null)
    {
        foreach ($this->data as $k => $v) {
            $this->assign($k, $v);
        }
        return parent::display($template);
    }
}
Form.php
require_once('BaseSmarty.php');

class Form extends BaseSmarty
{
    public function __construct()
    {
        parent::__construct();
    }

    protected function showForm()
    {
        $this->data['content_tpl'] = 'form.tpl';
        $this->data['params'] = array(
            'request'  => 'ご意見',
            'question' => '質問',
            'other'    => 'その他',
        );

        $this->display('template.tpl');
    }
}

$smart = new Form();
$smart->showForm();

まずこの時点でForm.phpにアクセスしたところページが表示されるはずが真っ白。

そしてこれは知人の「displayがprotectedになってるから以下の2行から呼び出せていない」

Form.php
$smart = new Form();
$smart->showForm();

という助言で解決。ここってクラス外って扱いなんですね。そりゃそうか。

Form.php
protected function display(

public function display(

ということで上記のようにpublicに修正。
Form.phpにアクセスすると確かに表示されている。成功か!

しかしここで疑問。
showForm()もprotectedでありクラス外、なはずが何故か呼び出せている…?

試しに

Form.php
$a = 1;
中略
$smart->a;

としても呼び出せない。publicならもちろん呼び出せる。

なんでだろう…?

cakePHPではこういった話もあるようだけど、うーん…分からない!

3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3