Programming Tutorials

Using class within a function in PHP

By: Albaity in PHP Tutorials on 2011-10-28  

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);
?>





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Latest Articles (in PHP)