Using class within a function in PHP

By: Albaity  

To use a PHP class within a function, you need first to load class OUT of the function and then you can use the class functions from your function.


example :
class Cart
{
    var $items;  // Items in our shopping cart
    // Add $num articles of $artnr to the cart
    function add_item ($artnr, $num)
    {
        $this->items[$artnr] += $num;
    }
    // Take $num articles of $artnr out of the cart
    function remove_item ($artnr, $num)
    {
        if ($this->items[$artnr] > $num) {
            $this->items[$artnr] -= $num;
            return true;
        } else {
            return false;
        }  
    }
}
------------------------
<?php
$cart = new Cart;
function additem($var1,$var2){
$cart->add_item($var1, $var2);
}
additem(1,10);
?>




Most Viewed Articles (in PHP )

Anonymous functions as properties in Classes in PHP

All possible substrings in a String in PHP

Decrypting files using GnuPG (GPG) via PHP

A Tutorial on Timezones and Timestamps

Integers and Floating-Point Numbers in PHP

XMLRPC for PHP - A simple client and server program

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

Function to force strict boolean values in PHP

Function to convert strings to strict booleans in PHP

Function to sort array by elements and count of element in PHP

Latest Articles (in PHP)

Comment on this tutorial