вопрос о классе в PHP - PullRequest
0 голосов
/ 21 июля 2010

проблема объема в классах PHP:

Почему это работает?

 class index extends Application
  {
        function ShowPage()
        {
            $smarty = new Smarty();         // construct class
            $smarty->assign('name', 'Ned');     // then call a method of class
            $smarty->display('index.tpl');
        }   

}

$ index_instance = new index;$ index_instance-> ShowPage ();

но это не работает?

class index extends Application
{

    function ShowPage()
    {

        $smarty->assign('name', 'Ned');
        $smarty->display('index.tpl');
    }   
}

$index_instance = new index;
$smarty = new Smarty();
$index_instance->ShowPage();

Ответы [ 3 ]

3 голосов
/ 21 июля 2010

Добро пожаловать в удивительный мир видимости переменных PHP.

Функции и методы не видят никаких переменных, определенных вне их. Вы должны использовать ключевое слово global, чтобы объявить, что вам нужен доступ к переменным, определенным вне области действия функции.

Это не сработает:

class Foo {
    public function bar() {
        echo $baz;
    }
}
$f = new Foo();
$baz = 'Hello world!';
$f->bar(); // "Notice: Undefined variable: ..."

Это будет работать:

class Foo2 {
    public function bar() {
        global $baz; // <- "I want $baz from the global scope"
        echo $baz;
    }
}
$f = new Foo2();
$baz = 'Hello world!';
$f->bar(); // "Hello world!"

Даже если это работает, вам следует избегать его использования. Есть лучшие способы прохождения во внешнем объекте. Один из способов называется « внедрение зависимостей », что является причудливым способом сказать «передать внешние зависимости во время построения». Например:

class Index extends Application {
    private $smarty;
    public function __construct(Smarty $smarty) {
        $this->smarty = $smarty;
    }
    public function showPage() {
        $smarty->assign('foo', 'bar');
        $smarty->display('index.tpl');
    }
}
$sm = new Smarty(...);
$whatever = new Index($sm);
$whatever->showPage();

Другим способом является использование реестра, который представляет собой шаблон, используемый для хранения вещей, которые в противном случае могли бы быть глобальными переменными. Давайте попробуем Zend Registry в качестве примера.

class Index extends Application {
    public function showPage() {
        $smarty = Zend_Registry::get('smarty');
        $smarty->assign('foo', 'bar');
        $smarty->display('index.tpl');
    }
}
$sm = new Smarty(...);
Zend_Registry::set('smarty', $sm);
$whatever = new Index();
$whatever->showPage();
1 голос
/ 21 июля 2010

Простой: потому что $ smarty не существует в области действия $ index_instance.

Если вы хотите создать экземпляр Smarty вне класса index, вам нужно передать smarty в экземпляр index:

class index extends Application 
{ 
    private $smarty = null;

    function __construct($smarty) {
        $this->smarty = $smarty;
    }

    function ShowPage() 
    { 

        $this->smarty->assign('name', 'Ned'); 
        $this->smarty->display('index.tpl'); 
    }    
} 

$smarty = new Smarty(); 
$index_instance = new index($smarty); 
$index_instance->ShowPage(); 
0 голосов
/ 21 июля 2010

Я сейчас использую метод внедрения зависимостей .

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

class index extends Application
{
    private $template_instance;

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

    function ShowPage()
    {
        $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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...