Jump to content

Calling functions within functions


jaoman

Recommended Posts

I teaching myself php, but I am coming from java and other compiled languages, so the process has been a little bumpy. I am trying to do something like this:

 

class my_class 
{

  function one ()
  {
     $two = two ();

     $three = three ();

     $five = $two + $three;

     return $five;
  }

  function two ()
  { 
     $two = 2;

    return $two;
  }

  function three ()
  {
     $three = 3;

     return $three;
  }
}

 

Unfortunately, I keep getting an error message saying that my call to two () is an undefined function. I am gathering from this that the scope of one () is not aware of the existence of two (). Is there a way to get around this so I can call two () and three () from one ()?

 

 

Link to comment
Share on other sites

Inside classes you have to use $this-> for member variables and member functions. Without, PHP will look for a normal variable (inside the function) and normal function (global function).

$two = $this->two();

$three = $this->three();

Link to comment
Share on other sites

You're calling $this outside of the class is most typical reason for this error.

 

That would make sense, wouldn't it. :P

 

Here's the offensive code:

 

class ThumbnailHelper
{

/*
 * @function: get_thumbnail
 * @description: Retrieves the thumbnail image of a random VirtueMart product
 * @param: None. 
 * @return: String with html to display an image. 
 */ 
 function get_thumbnail ()
 {
	 $category_list = $this->get_categories(); // The offending line! 

	 $category = array_rand ($category_list);

	$random_product = $this->get_random_product ($category); 

	 $image = $random_product->images [0]->displayMediaThumb('class="product-image"', true, 'class="modal"', true, true);

	 return $image; 

 }	 

/*
 * @function: get_random_product
 * @description: Retrieves a random product from a VM category.
 * @param: Category with at least one product. 
 * @return: VM Product object. 
 */ 
function get_random_product ($category)
{
	$product_model = VmModel::getModel ('product');
	$category_id = $category->virtuemart_category_id;

	$products = $product_model->getProductsInCategory ($category_id);
	$product_model->addImages ($products, 1);

	$product_population = count ($products);
	$random_product_key = rand (0, $product_population -1);

	return $products [$random_product_key];	

}

/*
 * @function: get_categories
 * @description: Retrieves an array of associative arrayss of the categories in VirtueMart.
 * @param: None.
 * @return: Array full of associative arrays. Keys are numbers. 
 */ 
function get_categories ()
{
	$category_model = VmModel::getModel ('category');

	$category_list = $category_model->getCategories ();

	return $category_list;
}

}

 

Unless being inside a class has some different meaning in php than elsewhere, I am clearly inside the class brackets. Grrr. :(

Link to comment
Share on other sites

I'm not getting an error on that line.  Running your code I just get the expected error on not having the VmModel class.  Perhaps the error points inside of that?  Could you post the whole error, including line number and ending file path. Sometimes the error points to a different file, and people miss that, out of frustration.

Link to comment
Share on other sites

I'm not getting an error on that line.  Running your code I just get the expected error on not having the VmModel class.  Perhaps the error points inside of that?  Could you post the whole error, including line number and ending file path. Sometimes the error points to a different file, and people miss that, out of frustration.

 

Okay. Here's the full error I am getting:

 

Fatal error: Using $this when not in object context in /home/sitename/public_html/building/modules/mod_DT/helper.php on line 49

 

The full file looks like this:

 

 

<?php
/* 
* @author: Jaoman
* @copyright (C) - Jaoman 2012
* 
* @package: mod_displaythumbnail
* @file: helper.php
* @purpose: This helper.php acts the Model for the mod_displaythumbnail module, providing logic support. 
* It connects to the VirtueMart framework, retrieves product data, parses data for image thumbnails location, 
* and returns the image.  
*/ 

// No direct access outside Joomla.
defined ('_JEXEC') or die ('Restricted access');

// Configures VirtueMart variables and stores them into cache.
if (!class_exists( 'VmConfig' )) require(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart'.DS.'helpers'.DS.'config.php');
VmConfig::loadConfig();

// Loads the language file of com_virtuemart.
JFactory::getLanguage()->load('com_virtuemart');

// Loads the VirtueMart image class. 
if (!class_exists( 'VmImage' )) require(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart'.DS.'helpers'.DS.'image.php');

// Loads VirtueMart Models. 
if (!class_exists( 'VirtueMartModelProduct' ))
{
   JLoader::import( 'product', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart' . DS . 'models' );
}

if (!class_exists ('VmModel')) require (JPATH_ADMINISTRATOR.DS.'helpers'.DS.'vmmodel.php');

// Loads VirtueMart category model. 
if (!class_exists( 'VirtueMartModelCategory' )) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'category.php');


class ThumbnailHelper
{

/*
 * @function: get_thumbnail
 * @description: Retrieves the thumbnail image of a random VirtueMart product
 * @param: None. 
 * @return: String with html to display an image. 
 */ 
 function get_thumbnail ()
 {
	 $category_list = $this->get_categories();

	 $category = array_rand ($category_list);

	 $random_product = $this->get_random_product ($category);

	 $image = $random_product->images [0]->displayMediaThumb('class="product-image"', true, 'class="modal"', true, true);

	 return $image; 
 } 


/*
 * @function: get_random_product
 * @description: Retrieves a random product from a VM category.
 * @param: Category with at least one product. 
 * @return: VM Product object. 
 */ 
function get_random_product ($category)
{
	$product_model = VmModel::getModel ('product');
	$category_id = $category->virtuemart_category_id;

	$products = $product_model->getProductsInCategory ($category_id);
	$product_model->addImages ($products, 1);

	$product_population = count ($products);
	$random_product_key = rand (0, $product_population -1);

	return $products [$random_product_key];	

}

/*
 * @function: get_categories
 * @description: Retrieves an array of associative arrayss of the categories in VirtueMart.
 * @param: None.
 * @return: Array full of associative arrays. Keys are numbers. 
 */ 
function get_categories ()
{
	// Returns the model object for VirtueMart categories.
	$category_model = VmModel::getModel ('category');

	// Returns an array of category objects. Each object is an associative array. 
	$category_list = $category_model->getCategories ();

	return $category_list;
}

}


?> 

 

You can't tell from here, but when you plug it into an editor, line 49 is "[]$category_list = $this->get_categories();[/i]".

 

I know the code itself works because, when I remove the other functions and just run all of it out of get_thumbnail, the module executes without a hitch. Does anyone have an answer?

Link to comment
Share on other sites

Where is the code that calls get_thumbnail()? Does it look like

ThumbnailHelper::get_thumbnail()

 

Yes, it does. The code is in another file.

 

 <?php 

// No direct access outside Joomla.
defined ('_JEXEC') or die ('Restricted access');

// Includes the helper file
require_once dirname(__FILE__).'/helper.php';

$thumbnail = ThumbnailHelper::get_thumbnail ();

// Get the layout
require JModuleHelper::getLayoutPath('mod_DT', $params->get('layout', 'default'));

?> 

 

$thumbnail then gets used by my view file to display the thumbnail. Unfortunately, this only seems to happen when my helper.php file doesn't rely on functions. :(

Link to comment
Share on other sites

jaoman, using :: as you are is attempting to statically calling the method. The method is not static.

You need to initiate the object.

So, instead of

$thumbnail = ThumbnailHelper::get_thumbnail();

Use:

$thumbnailHelper = new ThumbnailHelper();
$thumbnail = $thumbnailHelper->get_thumbnail();

 

Also, I'd like to correct a previous remark someone made in this thread.

$this is the keyword used to access an instance of an object.

self is not static in any way. It calls the class itself - not an instance of it, as $this does.

static is called similarly to self, but it refers to the static instance. If you want to refer to the class itself, and not any specific instance, self should be used instead.

 

Some examples:

class MyClass {
    public function myMethodA()
    {
        $stuff = 'hello';
        return $this->myMethodB($stuff);
    }
    
    private function myMethodB($stuff)
    {
        return $stuff . ' world';
    }
}

$myObject = new MyClass();
$theString = $myObject->myMethodA(); // Returns 'hello world'

 

A static version of the above example:

class MyStaticClass {
    public static function myMethodA()
    {
        $stuff = 'hello';
        return static::myMethodB($stuff);
    }
    
    private static function myMethodB($stuff)
    {
        return $stuff . ' world';
    }
}

$theString = MyStaticClass::myMethodA(); // Returns 'hello world'

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.