Jump to content

Working with Global Variables


SchweppesAle

Recommended Posts

hi, I'm not really sure why the following code is returning a "Call to a member function getBanners() on a non-object" error message.

 

  
   var $_model;
   
   function display ($tpl=null)
   {
          $this->_model = &$this->getModel();
  global $option,$mainframe, $_model;
          
  $Banners = $_model->getBanners();


  $this->assignRef('Banners', $Banners);
          parent::dislay($tpl);
   }

 

if I replace "$Banners = $_model->getBanners();" with  "$Banners = $this->_model->getBanners();" it works fine, I'm trying to shorten the code though.

Link to comment
https://forums.phpfreaks.com/topic/185854-working-with-global-variables/
Share on other sites

This is the entire class.  I thought I was already declaring the value of $_model with "$this->_model = &$this->getModel();"

 

<?php
defined('_JEXEC') or die ('restricted access');

jimport('joomla.application.component.view');

class JtbannersViewList extends JView
{
    
   var $_model;
   
   function display ($tpl=null)
   {
          $this->_model = &$this->getModel();
  global $option,$mainframe, $_model;
          
  $Banners = $_model->getBanners();


  $this->assignRef('Banners', $Banners);
          parent::dislay($tpl);
   }
   
}


?>

 

 

I thought I was already declaring the value of $_model with "$this->_model = &$this->getModel();"

 

Yes, but any variable declared outside of a method must be pre-pended with $this-> within a method to access it.

 

Also, using the global keyword within a class (or most anytime really) breaks your encapsulation. You may as well not bother using classes or functions at all.

I thought I was already declaring the value of $_model with "$this->_model = &$this->getModel();"

 

Yes, but any variable declared outside of a method must be pre-pended with $this-> within a method to access it.

 

Also, using the global keyword within a class (or most anytime really) breaks your encapsulation. You may as well not bother using classes or functions at all.

 

Good point.I just realized the manual wasn't referring to classes.

http://php.net/manual/en/language.variables.scope.php

 

This works though, probably much simpler too :P

 

defined('_JEXEC') or die ('restricted access');

jimport('joomla.application.component.view');

class JtbannersViewList extends JView
{
    
   
   function display($tpl=null)
   {
          $model = &$this->getModel();
  $Banners = $model->getBanners();


 $this->assignRef('Banners', $Banners);
         parent::display($tpl); 
   }
   
}


Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.