SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    Keep Moving Forward gold trophysilver trophybronze trophy
    Shaun(OfTheDead)'s Avatar
    Join Date
    Nov 2005
    Location
    Trinidad
    Posts
    3,727
    Mentioned
    43 Post(s)
    Tagged
    0 Thread(s)

    Import a Variable from a Function (so that It Can Be Used in Another Place)

    So I have a variable called $total that is solved by a function.

    I'd like to re-use this $total in a lower part of my PHP page, though, but for some reason I can't seem to import it to where it needs to be.

    This is part of the function...

    Code PHP:
    function solveTotal()
    			{
    			/* -- other stuff -- */
    			$total += $product_Price * $qty;
    			$total = number_format($total, 2);
    			}

    Then the HTML part of my PHP page basically goes...
    Code PHP:
    <?php echo solveTotal(); ?>
    			<?php
    			// Import Global Variable
    			$temp_total = $GLOBALS['total'];
    			?>
    			<!-- other stuff -->
    			<form action="" method="post">
    				<input type="hidden" name="amount" value="<?php echo($temp_total); ?>" />
    			<!-- rest of form -->

    When I view the source of the rendered PHP page, though, the value of that text input is always coming up as ""... No content at all.

    Does anyone have any idea what could be going wrong here??




    Trying to fill the unforgiving minute
    with sixty seconds' worth of distance run.

    Update on Sitepoint's Migration to Discourse

  2. #2
    SitePoint Zealot
    Join Date
    Jun 2007
    Posts
    150
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    function solveTotal()
    {
    /* -- other stuff -- */
    global $total;

    $total += $product_Price * $qty;
    $total = number_format($total, 2);
    }

    Might work. You might need to declare $total outside of the function first tho.

  3. #3
    SitePoint Wizard wheeler's Avatar
    Join Date
    Mar 2006
    Location
    Gold Coast, Australia
    Posts
    1,369
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    function solveTotal()
    {
       /* -- other stuff -- */
      $total += $product_Price * $qty;
      return number_format($total, 2);
    }
    <?php echo solveTotal(); ?>
    <?php
    // Import Global Variable
    $temp_total solveTotal();
    ?>
    <!-- other stuff -->
    <form action="" method="post">
    <input type="hidden" name="amount" value="<?php echo($temp_total); ?>" />
    <!-- rest of form -->
    To use variables like $product_Price in a function, you need to either pass it to the function

    solveTotal($product_Price)

    or inside the function at the top, type

    global $product_Price;
    Studiotime - Time Management for Web Developers
    to-do's, messages, invoicing, reporting - 30 day free trial!
    Thomas Multimedia Web Development

  4. #4
    Keep Moving Forward gold trophysilver trophybronze trophy
    Shaun(OfTheDead)'s Avatar
    Join Date
    Nov 2005
    Location
    Trinidad
    Posts
    3,727
    Mentioned
    43 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot, guys.

    That worked but now I'm having a second (and probably related) problem.

    The top of my function now reads...

    Code PHP:
    // Define Global Variables
    global $grandTotal;

    ...$total is solved in the middle, and then bottom goes...
    Code PHP:
    // Export Global Variables
    $grandTotal = $total;



    And now the HTML area of the page goes...
    Code PHP:
    <?php
    // Import Global Variables
    $temp_total = $GLOBALS['grandTotal'];
    $temp_count = $GLOBALS['grandCount'];
    ?>
     
    <form action="" method="post">
    	<input type="hidden" name="item_name" value="<?php echo("$temp_count"); ?> Items from Store" />
    	<input type="hidden" name="amount" value="<?php echo("$temp_total"); ?>" />



    Now the thing is this all worked perfectly when I defined $total as being the global variable, but then I thought that it would be risky to have so important a variable have so generic a name (as it might clash with another function somewhere) so I'm trying to commit it's value into the global variable called $grandTotal.

    This doesn't seem to be happening, though.

    I also tried...

    Code PHP:
    // Export Global Variables
    $GLOBALS['grandTotal'] = $total;

    ...with no luck.

    Suggestions??




    Trying to fill the unforgiving minute
    with sixty seconds' worth of distance run.

    Update on Sitepoint's Migration to Discourse

  5. #5
    Keep Moving Forward gold trophysilver trophybronze trophy
    Shaun(OfTheDead)'s Avatar
    Join Date
    Nov 2005
    Location
    Trinidad
    Posts
    3,727
    Mentioned
    43 Post(s)
    Tagged
    0 Thread(s)
    Hi.

    Okay I've figured it out.

    Apparently anything you have after the return part of your function isn't executed.

    Thanks for all the help.




    Trying to fill the unforgiving minute
    with sixty seconds' worth of distance run.

    Update on Sitepoint's Migration to Discourse

  6. #6
    SitePoint Wizard wheeler's Avatar
    Join Date
    Mar 2006
    Location
    Gold Coast, Australia
    Posts
    1,369
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    can I suggest that you replace
    Code:
    <?php echo("$temp_count"); ?>
    with
    Code:
    <?php echo $temp_count; ?>
    it does exactly the same thing just saves you typing a few extra characters!
    Studiotime - Time Management for Web Developers
    to-do's, messages, invoicing, reporting - 30 day free trial!
    Thomas Multimedia Web Development

  7. #7
    SitePoint Wizard cranial-bore's Avatar
    Join Date
    Jan 2002
    Location
    Australia
    Posts
    2,634
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Avoid globals. You are hard-wiring your function which is meant to be a relatively independent thing, into the environment in which it executes, losing flexibility and re-usability.

    Consider returning an associative array of values, or using a simple class. This allows you to access calculated values in the calling code without filling up the global scope with a lot of vars.

    Returning multiple values with array
    PHP Code:
    <?php

    function solveTotal() {
     
    $data['total'] = 0;
     
    $data['grand_total'] = 0;
     
    $data['count'] = 0;

     
    /* do stuff */

     
    return $data;
    }

    //CALLING CODE
    $priceData solveTotal();
    echo 
    "You ordered $priceData[count] products, for a total of $priceData[total] and a grand total of $priceData[grand_total]";
    ?>
    USING A CLASS
    PHP Code:
    <?php
    class pricing
    {
        public 
    $total;
        public 
    $grand_total;
        public 
    $count;

        public function 
    solveTotal() {
            
    /* do stuff */
           
    $this->total 101;
           
    $this->grand_total 203;
        }
    }

    //CALLING CODE
    $priceObject = new pricing();
    $priceObject->solveTotal();
    echo 
    '$' number_format($priceObject->total2);
    ?>

  8. #8
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I've had a similar problem to Shaun and have read about the evils of globals, though more to do with Javascript. Still, I guess the same basic principle applies.

    If I do what you've done there, cranial-bore, does that mean all functions have to be in classes? Because if I want to access anything in $priceObject within a function in the global scope, I'd still have to do global $priceObject, or at least that's what it seems like to me.

    PHP Code:
    <?php
    class pricing
    {
        public 
    $total;
        public 
    $grand_total;
        public 
    $count;

        public function 
    solveTotal() {
            
    /* do stuff */
           
    $this->total 101;
           
    $this->grand_total 203;
        }
    }

    //CALLING CODE
    $priceObject = new pricing();
    $priceObject->solveTotal();
    echo 
    '$' number_format($priceObject->total2);

    function 
    discount() {
      global 
    $priceObject;
      return 
    $priceObject->grand_total 0.2;
    }
    ?>
    I suppose the clear solution to that is to put discount() inside pricing. Does that mean functions in the global scope are also a bad idea? Also, does $priceObject not count as a "global variable" because it's an object? It's still in the global scope.

  9. #9
    ✯✯✯ silver trophybronze trophy php_daemon's Avatar
    Join Date
    Mar 2006
    Posts
    5,284
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Object is a regular variable of object data type; same rules apply.

    What you're doing, though, is mixing OO with procedural programing. Don't. If you're going OO, every function (i.e. method) should be a member of a particular class.

    In your example, discount() most likely should be a member of pricing class. If not, then some other class, in which case $priceObject would be passed to the discount() method (having both $priceObject and $discountObject in the same scope, of course)
    Saul

  10. #10
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Thanks, I get it now. I'm just used to Javascript's wonderfully lax way of doing things.

  11. #11
    SitePoint Wizard cranial-bore's Avatar
    Join Date
    Jan 2002
    Location
    Australia
    Posts
    2,634
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For the vast majority of cases it's preferable to pass and return rather than access globals.
    You can pass one object to another, or instantiate an object inside another.

    Discounting should probably be a method of the pricing object, but if it were complex enough (ie. needed multiple methods) it could be its own class.
    Remember that having paramaters/arguments in a class constructor means that the class can't be instantiated without them.
    This method can be used to avoid globals. You set the required object as an argument of the object constructor and then the calling code will error out if its not passed when creating the object.

    Consider:
    PHP Code:
    <?php
    class pricing
    {
       
    // .... (as before)
    }

    class 
    discount
    {
        private 
    $priceObj//private member object for use INSIDE this class
        
        /**
        * CONSTRUCTOR
        * Require $pricing (pricing object in our calling code)
        */
        
    public function __construct($pricing) {
            
    $this->priceObj $pricing;
        }

        public function 
    discount() {
           return 
    $this->priceObj->total 0.2;  //80% discount
        
    }
    }
    ?>
    Using classes within classes is a key aspect of their flexibility.

  12. #12
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    So, in the global scope, we would have this:

    PHP Code:
    $priceObject = new pricing();
    $priceObject->solveTotal();

    $discount = new discount($priceObject);
    $discount->discount(); 
    ? And in this scope we cannot access $discount->priceObj because it's private. Is that right?

  13. #13
    SitePoint Wizard cranial-bore's Avatar
    Join Date
    Jan 2002
    Location
    Australia
    Posts
    2,634
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yep, exactly right.

    Its worth remembering that by default in PHP5 objects are passed by reference. The price object inside the discount object is just a reference to the original object. This saves memory.

    So while you can't access $discount->priceObj, accessing $priceObject is actually the same thing, because of the reference.

  14. #14
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I see. This has been very helpful, cheers.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •