php - class

A class is a collection of variables and functions working with these variables. Variables are defined by var and functions by function. A class is defined using the following syntax:

<?php
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;
   } elseif (

    $this->items[$artnr] == $num) {
    unset(
$this->items[$artnr]);
    return
true;
   } else {
    return
false;
   }
  }
}
 

?>
 
This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.
Warning You can NOT break up a class definition into multiple files. You also can NOT break a class definition into multiple PHP blocks, unless the break is within a method declaration. The following will not work:

<?php
class test { 
?>
<?php
 
function test() {
   print
'OK';
  }
}
 

?>

However, the following is allowed:

<?php
class test {
  function
test() {?>  

<?php
  
print 'OK';
  }
}
 

?>

The following cautionary notes are valid for PHP 4.
Caution The name stdClass is used internally by Zend and is reserved. You cannot have a class named stdClass in PHP.
Caution The function names __sleep and __wakeup are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them. See below for more information.
Caution PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.
In PHP 4, only constant initializers for var variables are allowed. To initialize variables with non-constant values, you need an initialization function which is called automatically when an object is being constructed from the class. Such a function is called a constructor (see below).
<?php
class Cart {
 
/* None of these will work in PHP 4. */
 
var $todays_date = date("Y-m-d");
  var
$name = $firstname;
  var
$owner = 'Fred ' . 'Jones';
 
/* Arrays containing constant values will, though. */
 
var $items = array("VCR", "TV");
}
/* This is how it should be done. */

class Cart {
  var
$todays_date;
  var
$name;
  var
$owner;
  var
$items = array("VCR", "TV");

  function
Cart() {
  
$this->todays_date = date("Y-m-d");
  
$this->name = $GLOBALS['firstname'];
  
/* etc. . . */
 
}
}
 

?>
Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.

<?php
$cart
= new Cart;$cart->add_item("10", 1);
$another_cart = new Cart;$another_cart->add_item("0815", 3); 

?>

This creates the objects $cart and $another_cart, both of the class Cart. The function add_item() of the $cart object is being called to add 1 item of article number 10 to the $cart. 3 items of article number 0815 are being added to $another_cart.
Both, $cart and $another_cart, have functions add_item(), remove_item() and a variable items. These are distinct functions and variables. You can think of the objects as something similar to directories in a filesystem. In a filesystem you can have two different files README.TXT, as long as they are in different directories. Just like with directories where you'll have to type the full pathname in order to reach each file from the toplevel directory, you have to specify the complete name of the function you want to call: in PHP terms, the toplevel directory would be the global namespace, and the pathname separator would be ->. Thus, the names $cart->items and $another_cart->items name two different variables. Note that the variable is named $cart->items, not $cart->$items, that is, a variable name in PHP has only a single dollar sign.

<?php 
// correct, single $
$cart->items = array("10" => 1);
// invalid, because $cart->$items becomes $cart->"" 

$cart->$items = array("10" => 1);
// correct, but may or may not be what was intended:
// $cart->$myvar becomes $cart->items
 

$myvar = 'items';$cart->$myvar = array("10" => 1); 
?>
 
Within a class definition, you do not know under which name the object will be accessible in your program: at the time the Cart class was written, it was unknown whether the object would be named $cart, $another_cart, or something else later. Thus, you cannot write $cart->items within the Cart class itself. Instead, in order to be able to access its own functions and variables from within a class, one can use the pseudo-variable $this which can be read as 'my own' or 'current object'. Thus, '$this->items[$artnr] += $num' can be read as 'add $num to the $artnr counter of my own items array' or 'add $num to the $artnr counter of the items array within the current object'.
Note: The $this pseudo-variable is not usually defined if the method in which it is hosted is called statically. This is not, however, a strict rule: $this is defined if a method is called statically from within another object. In this case, the value of $this is that of the calling object. This is illustrated in the following example:
<?php

class A{
  function
foo(){
   if (isset(
$this)) {
   echo
'$this is defined (';
   echo
get_class($this);
   echo
")\n";
  } else {
   echo
"\$this is not defined.\n";
  }
  }
}

class
B{
function
bar()
{
A::foo();
}
}
$a = new A();$a->foo();A::foo();$b = new B();$b->bar();B::bar();?>

The above example will output:
$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

php - chunk_split

Split a string into smaller chunks

Description

string chunk_split ( string $body [, int $chunklen [, string $end]] )
Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode() output to match RFC 2045 semantics. It inserts end every chunklen characters.

Parameters



body
The string to be chunked.
chunklen
The chunk length. Defaults to 76.
end
The line ending sequence. Defaults to "\r\n".

Return Values

Returns the chunked string.

Examples


Example 2383. chunk_split() example

<?php 
// format $data using RFC 2045 semantics 
$new_string = chunk_split(base64_encode($data));

?>

php - chroot

Change the root directory

Description

bool chroot ( string $directory )
Changes the root directory of the current process to directory.
This function is only available if your system supports it and you're using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.

Parameters



directory
The new directory

Return Values

Returns TRUE on success or FALSE on failure.

php - chr

Return a specific character

Description

string chr ( int $ascii )
Returns a one-character string containing the character specified by ascii.
This function complements ord().

Parameters



ascii
The ascii code.

Return Values

Returns the specified character.

Examples


Example 2382. chr() example

<?php

$str
= "The string ends in escape: ";

$str .= chr(27); /* add an escape character at the end of $str */

/* Often this is more useful */
$str = sprintf("The string ends in escape: %c", 27);

?>

php - chown

Changes file owner

Description

bool chown ( string $filename, mixed $user )
Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.

Parameters


filename
Path to the file.
user
A user name or number.

Return Values

Returns TRUE on success or FALSE on failure.

php - chmod

Changes file mode
bool chmod ( string $filename, int $mode )

Attempts to change the mode of the specified file to that given in mode.

filename
Path to the file.
mode
Note that mode is not automatically assumed to be an octal value, so strings (such as "g+w") will not work properly. To ensure the expected operation, you need to prefix mode with a zero (0):
<?php  chmod("/somedir/somefile", 755); // decimal; probably incorrect chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect chmod("/somedir/somefile", 0755); // octal; correct value of mode ?>
The mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.
<?php // Read and write for owner, nothing for everybody else    chmod("/somedir/somefile", 0600); // Read and write for owner, read for everybody else    chmod("/somedir/somefile", 0644); // Everything for owner, read and execute for others   chmod("/somedir/somefile", 0755); // Everything for owner, read and execute for owner's group    chmod("/somedir/somefile", 0750); ?>

Return Values

Returns TRUE on success or FALSE on failure.

php - chgrp

Changes file group

bool chgrp ( string $filename, mixed $group )

Attempts to change the group of the file filename to group.
Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

Parameters


filename
Path to the file.
group
A group name or number.

Return Values

Returns TRUE on success or FALSE on failure.

php - checkdnsrr

Check DNS records corresponding to a given Internet host name or IP address

Description

int checkdnsrr ( string $host [, string $type] )
Searches DNS for records of type type corresponding to host.

Parameters



host
host may either be the IP address in dotted-quad notation or the host name.
type
type may be any one of: A, MX, NS, SOA, PTR, CNAME, AAAA, A6, SRV, NAPTR, TXT or ANY. The default is MX.

Return Values

Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

php - checkdate

Validate a Gregorian date

Description

bool checkdate ( int $month, int $day, int $year )
Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.

Parameters


month
The month is between 1 and 12 inclusive.
day
The day is within the allowed number of days for the given month. Leap years are taken into consideration.
year
The year is between 1 and 32767 inclusive.

Return Values

Returns TRUE if the date given is valid; otherwise returns FALSE.

Examples


Example 430. checkdate() example
<?php
 
var_dump(checkdate(12, 31, 2000)); 

var_dump(checkdate(2, 29, 2001)); 

?>
The above example will output:
bool(true)
bool(false)

php - chdir

Change directory

Description

bool chdir ( string $directory )
Changes PHP's current directory to directory.

Parameters


directory
The new current directory

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example 494. chdir() example

<?php

// current directory 

echo getcwd() . "\n";
 

chdir('public_html');

// current directory

echo getcwd() . "\n";

?>


The above example will output something similar to:
/home/vincent
/home/vincent/public_html

php - ceil

Round fractions up

Description

float ceil ( float $value )
Returns the next highest integer value by rounding up value if necessary.

Parameters


value
The value to round

Return Values

value rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.

Examples


Example 1125. ceil() example

<?php

echo ceil(4.3); // 5

echo ceil(9.999); // 10
echo ceil(-3.14); // -3

?>

php - ccvs_void

Perform a full reversal on a completed transaction

Description

string ccvs_void ( string $session, string $invoice )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_textvalue

Get text return value for previous function call

Description

string ccvs_textvalue ( string $session )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_status

Check the status of an invoice

Description

string ccvs_status ( string $session, string $invoice )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_sale

Transfer funds from the credit card holder to the merchant

Description

string ccvs_sale ( string $session, string $invoice )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_reverse

Perform a full reversal on an already-processed authorization

Description

string ccvs_reverse ( string $session, string $invoice )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_return

Transfer funds from the merchant to the credit card holder.

Description

string ccvs_return ( string $session, string $invoice )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_report

Return the status of the background communication process

Description

string ccvs_report ( string $session, string $type )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_new

Create a new, blank transaction

Description

string ccvs_new ( string $session, string $invoice )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_lookup

Look up an item of a particular type in the database #

Description

string ccvs_lookup ( string $session, string $invoice, int $inum )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_init

Initialize CCVS for use

Description

string ccvs_init ( string $name )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_done

Terminate CCVS engine and do cleanup work

Description

string ccvs_done ( string $sess )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_delete

Delete a transaction

Description

string ccvs_delete ( string $session, string $invoice )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_count

Find out how many transactions of a given type are stored in the system

Description

int ccvs_count ( string $session, string $type )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_command

Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API

 

Description

string ccvs_command ( string $session, string $type, string $argval )
Warning This function is currently not documented; only the argument list is available.

ccvs_auth

Perform credit authorization test on a transaction

Description

string ccvs_auth ( string $session, string $invoice )
Warning This function is currently not documented; only the argument list is available.

php - ccvs_add

Description

string ccvs_add ( string $session, string $invoice, string $argtype, string $argval )
Warning This function is currently not documented; only the argument list is available.

php - call_user_func_array

Description

mixed call_user_func_array ( callback $function, array $param_arr )
Call a user defined function with the parameters in param_arr.

Parameters


function
The function to be called.
param_arr
The parameters to be passed to the function, as an indexed array.

Return Values

Returns the function result, or FALSE on error.

Examples


Example 742. call_user_func_array() example
<?php

function debug($var, $val)
{
echo
"***DEBUGGING\nVARIABLE: $var\nVALUE:";
if (
is_array($val) || is_object($val) || is_resource($val)) {
print_r($val);
} else {
echo
"\n$val\n";
}
echo
"***\n";
}
$c = mysql_connect();

$host = $_SERVER["SERVER_NAME"];
call_user_func_array('debug', array("host", $host));call_user_func_array('debug', array("c", $c));

call_user_func_array('debug', array("_POST", $_POST));


?>

php - call_user_func

Description

mixed call_user_func ( callback $function [, mixed $parameter [, mixed $...]] )
Call a user defined function given by the function parameter.

Parameters


function
The function to be called. Class methods may also be invoked statically using this function by passing array($classname, $methodname) to this parameter.
parameter
Zero or more parameters to be passed to the function.
Note: Note that the parameters for call_user_func() are not passed by reference. 
<?php 
function increment(&$var) {
$var++;
}
$a = 0;
call_user_func('increment', $a);
echo $a; // 0
call_user_func_array('increment', array(&$a)); // You can use this instead
echo $a; // 1 
?>

Return Values

Returns the function result, or FALSE on error.

Examples


Example 743. call_user_func() example
<?php
function barber($type)
{
echo
"You wanted a $type haircut, no problem";
}

call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

Example 744. Using a class method


<?php

class myclass {

function
say_hello()
{
echo
"Hello!\n";
}
}
$classname = "myclass";
call_user_func(array($classname, 'say_hello'));

?>

php - cal_to_jd

Description

int cal_to_jd ( int $calendar, int $month, int $day, int $year )
cal_to_jd() calculates the Julian day count for a date in the specified calendar. Supported calendars are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters



calendar
Calendar to convert from, one of CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH or CAL_FRENCH.
month
The month as a number, the valid range depends on the calendar
day
The day as a number, the valid range depends on the calendar
year
The year as a number, the valid range depends on the calendar

Return Values

A Julian Day number.

php - cal_info

Description

array cal_info ( [int $calendar] )
cal_info() returns information on the specified calendar.
Calendar information is returned as an array containing the elements calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar are as follows:
  • 0 or CAL_GREGORIAN - Gregorian Calendar
  • 1 or CAL_JULIAN - Julian Calendar
  • 2 or CAL_JEWISH - Jewish Calendar
  • 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array.

Parameters



calendar
Calendar to return information for. If no calendar is specified information about all calendars is returned.

Return Values


ChangeLog


Version Description
Since 5.0 The calendar parameter becomes optional and defaults to "all calendars" if omitted.

Examples


Example 358. cal_info() example


<?php

$info
= cal_info(0);

print_r($info);

?>

The above example will output:
Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)

php - cal_from_jd

Description

array cal_from_jd ( int $jd, int $calendar )
cal_from_jd() converts the Julian day given in jd into a date of the specified calendar. Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters



jd
Julian day as integer
calendar
Calendar to convert to

Return Values

Returns an array containing calendar information like month, day, year, day of week, abbreviated and full names of weekday and month and the date in string form "month/day/year".

Examples


Example 357. cal_from_jd() example


<?php

$today
= unixtojd(mktime(0, 0, 0, 8, 16, 2003));

print_r(cal_from_jd($today, CAL_GREGORIAN));

?>

The above example will output:
Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

php - cal_days_in_month

Description

int cal_days_in_month ( int $calendar, int $month, int $year )
This function will return the number of days in the month of year for the specified calendar.

Parameters



calendar
Calendar to use for calculation
month
Month in the selected calendar
year
Year in the selected calendar

Return Values

The length in days of the selected month in the given calendar

Examples


Example 356. cal_days_in_month() example


<?php

$num
= cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31

echo "There was $num days in August 2003";

?>

php - bzwrite

Description

int bzwrite ( resource $bz, string $data [, int $length] )
bzwrite() writes a string into the given bzip2 file stream.

Parameters


bz
The file pointer. It must be valid and must point to a file successfully opened by bzopen().
data
The written data.
length
If supplied, writing will stop after length (uncompressed) bytes have been written or the end of data is reached, whichever comes first.

Return Values

Returns the number of bytes written, or FALSE on error.

Examples


Example 355. bzwrite() example


<?php

$str
= "uncompressed data";

$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));bzclose($bz);

?>

php - bzread

Description

string bzread ( resource $bz [, int $length] )
bzread() reads from the given bzip2 file pointer.
Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

Parameters



bz
The file pointer. It must be valid and must point to a file successfully opened by bzopen().
length
If not specified, bzread() will read 1024 (uncompressed) bytes at a time.

Return Values

Returns the uncompressed data, or FALSE on error.

Examples


Example 354. bzread() example


<?php

$file
= "/tmp/foo.bz2";$bz = bzopen($file, "r") or die("Couldn't open $file");
$decompressed_file = '';
while (!
feof($bz)) {
$decompressed_file .= bzread($bz, 4096);
}
bzclose($bz);

echo
"The contents of $file are: <br />\n";
echo
$decompressed_file;
?>

php - bzopen

Description

resource bzopen ( string $filename, string $mode )
bzopen() opens a bzip2 (.bz2) file for reading or writing.

Parameters



filename
The name of the file to open.
mode
Similar to the fopen() function ('r' for read, 'w' for write, etc.).

Return Values

If the open fails, bzopen() returns FALSE, otherwise it returns a pointer to the newly opened file.

Examples


Example 353. bzopen() example


<?php

$file
= "/tmp/foo.bz2";$bz = bzopen($file, "r") or die("Couldn't open $file for reading");
bzclose($bz);
?>

php - bzerror

Description

array bzerror ( resource $bz )
Returns the error number and error string of any bzip2 error returned by the given file pointer.

Parameters



bz
The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns an associative array, with the error code in the errno entry, and the error message in the errstr entry.

Examples


Example 352. bzerror() example


<?php

$error
= bzerror($bz);

echo
$error["errno"];
echo
$error["errstr"];

?>