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);
?>
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
PHP convert string to lower case
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Error: Length parameter must be greater than 0
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8