Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

php - class_implements

Return the interfaces which are implemented by the given class

Description

array class_implements ( mixed $class [, bool $autoload] )
This function returns an array with the names of the interfaces that the given class and its parents implement.

Parameters


class
An object (class instance) or a string (class name).
autoload
Whether to allow this function to load the class automatically through the __autoload magic method. Defaults to TRUE.

Return Values

Returns an array or FALSE on error.

ChangeLog


Version Description
5.1.0 Added the option to pass the class parameter as a string. Added the autoload parameter.

Examples


Example 2297. class_implements() example

<?php
interface foo { }
class
bar implements foo {}
print_r(class_implements(new bar));
// since PHP 5.1.0 you may also specify the parameter as a string

print_r(class_implements('bar'));


function
__autoload($class_name) {
require_once
$class_name . '.php';
}
// use __autoload to load the 'not_loaded' class

print_r(class_implements('not_loaded', true));
?> 


The above example will output something similar to:
Array
(
    [foo] => foo
)

Array
(
    [interface_of_not_loaded] => interface_of_not_loaded
)

php - class_exists

class_exists — Checks if the class has been defined

Description

bool class_exists ( string $class_name [, bool $autoload] )
This function checks whether or not the given class has been defined.

Parameters


class_name
The class name. The name is matched in a case-insensitive manner.
autoload
Whether or not to call __autoload by default. Defaults to TRUE.

Return Values

Returns TRUE if class_name is a defined class, FALSE otherwise.

ChangeLog


Version Description
5.0.2 No longer returns TRUE for defined interfaces. Use interface_exists().
5.0.0 The autoload parameter was added.

Examples


Example 365. class_exists() example
<?php 
// Check that the class exists before trying to use it 
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>

Example 366. autoload parameter example
<?php
function __autoload($class)
{
include(
$class . '.php');

// Check to see whether the include declared the class
if (!class_exists($class, false)) {
trigger_error("Unable to load class: $class", E_USER_WARNING);
}
}

if (
class_exists('MyClass')) {
$myclass = new MyClass();
}
?>

php - Class/Object Functions

These functions allow you to obtain information about classes and instance objects. You can obtain the name of the class to which an object belongs, as well as its member properties and methods. Using these functions, you can find out not only the class membership of an object, but also its parentage (i.e. what class is the object class extending).

Requirements

No external libraries are needed to build this extension.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Examples

In this example, we first define a base class and an extension of the class. The base class describes a general vegetable, whether it is edible or not and what is its color. The subclass Spinach adds a method to cook it and another to find out if it is cooked.

Example 363. classes.inc
<?php
// base class with member properties and methodsclass Vegetable {

var
$edible;
var
$color;

function
Vegetable($edible, $color="green")
{
$this->edible = $edible;
$this->color = $color;
}

function
is_edible()
{
return
$this->edible;
}

function
what_color()
{
return
$this->color;
}

}
// end of class Vegetable

// extends the base class
class Spinach extends Vegetable {

var
$cooked = false;

function
Spinach()
{
$this->Vegetable(true, "green");
}

function
cook_it()
{
$this->cooked = true;
}

function
is_cooked()
{
return
$this->cooked;
}

}
// end of class Spinach
?>

We then instantiate 2 objects from these classes and print out information about them, including their class parentage. We also define some utility functions, mainly to have a nice printout of the variables.

Example 364. test_script.php
<pre>
<?php
include "classes.inc";
// utility functions
function print_vars($obj)
{
foreach (
get_object_vars($obj) as $prop => $val) {
echo
"\t$prop = $val\n";
}
}

function
print_methods($obj)
{
$arr = get_class_methods(get_class($obj));
foreach (
$arr as $method) {
echo
"\tfunction $method()\n";
}
}

function
class_parentage($obj, $class)
{
if (
is_subclass_of($GLOBALS[$obj], $class)) {
echo
"Object $obj belongs to class " . get_class($$obj);
echo
" a subclass of $class\n";
} else {
echo
"Object $obj does not belong to a subclass of $class\n";
}
}
// instantiate 2 objects
$veggie = new Vegetable(true, "blue");$leafy = new Spinach();
// print out information about objectsecho "veggie: CLASS " . get_class($veggie) . "\n";
echo
"leafy: CLASS " . get_class($leafy);
echo
", PARENT " . get_parent_class($leafy) . "\n";
// show veggie propertiesecho "\nveggie: Properties\n";print_vars($veggie);
// and leafy methodsecho "\nleafy: Methods\n";print_methods($leafy);

echo
"\nParentage:\n";class_parentage("leafy", "Spinach");class_parentage("leafy", "Vegetable");?></pre>
One important thing to note in the example above is that the object $leafy is an instance of the class Spinach which is a subclass of Vegetable, therefore the last part of the script above will output:
[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

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.