Built in classes in php

Built in classes in php

PHP comes with a pretty large set of features that are already built into it. Most of them are available as plain functions that can be called from anywhere in your code. This is a big difference to languages where the standard library is completely organized into modules and classes. When PHP first became really popular, object oriented programming was not nearly as widely adopted as today and PHP adopted the style of the C programming language that also uses globally available functions. Later, mostly after PHP 5 was widely is use, some of the core functionality was also made available via classes, the probably most common example being the DateTime class.

In today’s PHP, the «old way» of just calling functions is still available and it’s often the only way to access a feature of the PHP runtime. Some things have also gotten object oriented API’s (like DateTime ) and some new features are only available as object oriented APIs like the classes from the SPL (Standard PHP Library).

Built-in Functions

In the previous chapter, we already encountered array_map() and usort() . Both are functions that provide common operations on arrays. The PHP manual has a complete list of PHP’s array functions.

A common source of errors and annoyance is that the arguments of these functions are not always consistent. For example, array_map() expects the first argument to be a function and the second to be an array while usort() expects them the other way around. array_reduce() also expects the callback function as the second argument.

Читайте также:  Определяет цвет шрифта html

Another inconsistency is in the function names. Some are written with underscores, others in one word, for example get_class() and gettype() .

The reason for this is that for a long time, people have added features to PHP without worrying about consistency of the APIs and to maintain backwards compatibility this can’t be changed easily anymore. You will need to pay close attention to the order of arguments for PHP’s built-in functions.

String functions

PHP has a lot of functions to handle strings. The problem with them is that most of them don’t work well with Unicode strings. Take substr() for example, it’s supposed to extract a part of a string but when we use it with something like German umlauts, it messes up the characters:

$str = "äöü"; echo substr($str, 0, 1) . PHP_EOL; //echoes "�" instead of the correct "ä" echo mb_subtsr($str, 0, 1, "utf-8"); //echoes "ä" correctly with "utf-8" as encoding argument 

When using string functions with input that potentially has Unicode characters in it, always use the mb_ version of it, if there is one, and by default, you should use «utf-8» as your encoding throughout your application to avoid any issues caused by not matching encodings. If you have to receive or send data to external systems in different encodings, convert the encoding right at the edges of your application and keep everything as UTF-8 internally.

The mb_ string functions are provided by a PHP extension called «mbstring», it is usually installed by default.

These are some of the most commonly used string functions. You should definitely read about those:

Array functions

Apart from string operation, handling arrays is hugely important in PHP. We will see in one of the chapters, why. Most array operations are available as functions in PHP. Here are some of the most used ones:

  • array_map()
  • sort() , usort() and ksort()
  • array_filter()
  • array_push() , array_pop() , array_shift() and array_unshift()
  • array_key_exists()
  • array_merge()
  • array_slice()
  • count()
  • array_values() and array_keys()
  • explode() and implode()

File IO functions

Reading and writing files is a very common task in almost any programming language. PHP has several ways of doing that.

The simplest way is to use file_get_contents() and file_put_contents() . These two function read and write entire files from/into a string. They are very convenient but can cause problems with larger files because they load the entire contents of the file into memory at once.

There are also fopen() , fread() , fwrite() and fclose() . They provide far more control over how files are read/written. There will be a dedicated chapter on file IO where we explore these in more detail.

Other functions

These are a few more commonly used functions that you’ll probably need often:

Builtin Classes

As object oriented style got more and more popular with PHP, new features have also gotten class based APIs. The most common one being DateTime and its related classes.

DateTime

A DateTime object represents a single point in time in PHP with up to microsecond precision. It enables you to reliably do date manipulations like «take NOW and add 423 days and 7 hours», correctly compare dates or describe and calculate time intervals like «the time span from NOW to the end of the year». Here are a few examples:

Note: Don’t forget to set the timezone for your application with date_default_timezone_set() .

$towel_day = new DateTime("2015-05-25"); //http://en.wikipedia.org/wiki/Towel_Day var_dump($towel_day); /* prints: object(DateTime)#1 (3) < ["date"]=>string(26) "2015-05-25 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" > */ 

As you can see, if you don’t specify parts of the date, PHP set’s them to 0. So, when you make a DateTime with no time information, PHP assumes, you mean «00:00:00» on that day for example.

For output it’s usually a good idea to use a date format. DateTime objects have a format() method that does that. It uses a special syntax for defining date formats from the date() function:

$towel_day_afternoon = new DateTime("2015-05-25 16:30:00"); //now print the date in a format that's common in the USA echo $towel_day_afternoon->format("F j Y, g:h a") . PHP_EOL; //now print it as an ISO-8601 time stamp, PHP has a shortcut for that echo $towel_day_afternoon->format("c") . PHP_EOL; 
//How many days is it from the start of 2015 to Towel Day? $towel_day = new DateTime("2015-05-25"); $january_first = new DateTime("2015-01-01"); $diff = $january_first->diff($towel_day); //$diff is a DateInterval object: var_dump($diff); /* prints: object(DateInterval)#6 (15) < ["y"]=>int(0) ["m"]=> int(4) ["d"]=> int(23) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(0) ["days"]=> int(144) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) > */ //to print only the total number of days: echo $diff->days . PHP_EOL; */ 

When doing any arithmetic with time or date values, always use the DateTime (and related) classes. There are so many edge cases in date/time calculations that you certainly don’t want to do it yourself.

Источник

Built in classes in php

This section lists standard predefined classes. Miscellaneous extensions define other classes which are described in their reference.

Standard Defined Classes

These classes are defined in the standard set of functions included in the PHP build.

Directory Created by dir() . stdClass A generic empty class created as a result of typecasting to object or various standard functions. __PHP_Incomplete_Class Possibly created by unserialize() . Exception ErrorException php_user_filter Closure The predefined final class Closure is used for representing anonymous functions. Generator The predefined final class Generator is used for representing generators. ArithmeticError AssertionError DivisionByZeroError Error Throwable ParseError TypeError

Special classes

Following identifiers may not be used as a class name as they have special purpose.

self Current class. static Current class in runtime. parent Parent class.

User Contributed Notes 7 notes

if you want a Dynamic class you can extend from, add atributes AND methods on the fly you can use this:
class Dynamic extends stdClass public function __call ( $key , $params ) if(!isset( $this ->< $key >)) throw new Exception ( «Call to undefined method » . get_class ( $this ). «::» . $key . «()» );
$subject = $this ->< $key >;
call_user_func_array ( $subject , $params );
>
>
?>

this will accept both arrays, strings and Closures:
$dynamic -> myMethod = «thatFunction» ;
$dynamic -> hisMethod = array( $instance , «aMethod» );
$dynamic -> newMethod = array( SomeClass , «staticMethod» );
$dynamic -> anotherMethod = function() echo «Hey there» ;
>;
?>

then call them away =D

If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I’d advise you to implement ::__set_state().

/**
* An implementation of var_export() that is compatible with instances
* of stdClass.
* @param mixed $variable The variable you want to export
* @param bool $return If used and set to true, improved_var_export()
* will return the variable representation instead of outputting it.
* @return mixed|null Returns the variable representation when the
* return parameter is used and evaluates to TRUE. Otherwise, this
* function will return NULL.
*/
function improved_var_export ( $variable , $return = false ) if ( $variable instanceof stdClass ) $result = ‘(object) ‘ . improved_var_export ( get_object_vars ( $variable ), true );
> else if ( is_array ( $variable )) $array = array ();
foreach ( $variable as $key => $value ) $array [] = var_export ( $key , true ). ‘ => ‘ . improved_var_export ( $value , true );
>
$result = ‘array (‘ . implode ( ‘, ‘ , $array ). ‘)’ ;
> else $result = var_export ( $variable , true );
>

if (! $return ) print $result ;
return null ;
> else return $result ;
>
>

// Example usage:
$obj = new stdClass ;
$obj -> test = ‘abc’ ;
$obj -> other = 6.2 ;
$obj -> arr = array ( 1 , 2 , 3 );

improved_var_export ((object) array (
‘prop1’ => true ,
‘prop2’ => $obj ,
‘assocArray’ => array (
‘apple’ => ‘good’ ,
‘orange’ => ‘great’
)
));

/* Output:
(object) array (‘prop1’ => true, ‘prop2’ => (object) array (‘test’ => ‘abc’, ‘other’ => 6.2, ‘arr’ => array (0 => 1, 1 => 2, 2 => 3)), ‘assocArray’ => array (‘apple’ => ‘good’, ‘orange’ => ‘great’))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn’t formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().

There comes improved version of amazing snippet posted by (spark at limao dot com dot br) which allows dynamic methods generations and works as versatile extension of StdClass:

This one is faster, optimised for closures, and will work only with closures. Compatible: >= PHP 5.6

class Dynamic extends \ stdClass
public function __call ( $key , $params )
if ( ! isset( $this ->< $key >)) throw new Exception ( «Call to undefined method » . __CLASS__ . «::» . $key . «()» );
>

$dynamic = new Dynamic ();
$dynamic -> anotherMethod = function () echo «Hey there» ;
>;
$dynamic -> randomInt = function ( $min , $max ) return mt_rand ( $min , $max ); // random_int($min, $max); // >;

var_dump (
$dynamic -> randomInt ( 1 , 11 ),
$dynamic -> anotherMethod ()
);
?>

This will accept arrays, strings and Closures but is a bit slower due to call_user_func_array

class Dynamic extends \ stdClass
public function __call ( $key , $params )
if ( ! isset( $this ->< $key >)) throw new Exception ( «Call to undefined method » . __CLASS__ . «::» . $key . «()» );
>

return call_user_func_array ( $this ->< $key >, $params );
>
>

?>

Usage examples:
$dynamic = new Dynamic ();
$dynamic -> myMethod = «thatFunction» ;
$dynamic -> hisMethod = array( $dynamic , «randomInt» );
$dynamic -> newMethod = array( SomeClass , «staticMethod» );
$dynamic -> anotherMethod = function () echo «Hey there» ;
>;
$dynamic -> randomInt = function ( $min , $max ) return mt_rand ( $min , $max ); // random_int($min, $max); // >;

var_dump (
$dynamic -> randomInt ( 1 , 11 ),
$dynamic -> anotherMethod (),
$dynamic -> hisMethod ()
);

Источник

Оцените статью