Php – Built in classes on php.net
I know this is very newbyish but I have been using php.net for refernce for at least 2 years now to look up the built in functions and I am just noticing that there is some built in classes as well like here for an example http://www.php.net/manual/en/datetime.settimezone.php I am now remembering seeing some functions in the past that would show an example in procedural way and in class way as well, of course when I wanted to find one of these for an example I couldn’t though.
The question here is has these classes been there on php.net for a long time? Also is there any benefit of using one of the built in classes over a built in function?
Best Solution
is there any benefit of using one of the built in classes over a built in function?
It all depends on how you did the conception and developpement of your application :
- if your application is based on Object-Oriented Programming, it makes sense to use the OO-interface (ie, classes)
- if your application is based on procedural programming, it probably makes more sense to use the procedural-interface (ie, functions)
In any case, of course, you can choose one API or the other, as you see fit — the two points I wrote are no more than «logical guidelines», I’d say.
has these classes been there on php.net for a long time?
Well, I’m guessing, for classes that belong to extensions bundled with PHP (like mysqli, for instance), that they are there since the extension they document exists.
In the case of mysqli, it means PHP 5, it seems (see, for instance, the PHP’s version number on top of this page) — so, I’d say since something like 2005 (I didn’t check the date, but it’s something like that)
As a sidenote, you have to take care about the fact that php.net hosts documentation for :
- functions / classes that are always bundled with PHP — or, at least, almost never de-activated ; for instance, session
- functions / classes that are exposed by extensions that often come from PHP, and are hosted on the same SVN as PHP’s sources. But not necessarily always compiled or actived — for instance, mysqli or soap (I’ve worked on a server some time ago where I’ve had to compile those myself)
- functions / classes that are exposed by extensions that are not even hosted on the SVN containing PHP’s source-code (or, in another directory, different from PHP’s one) — many of those extensions are available as PECL packages — for instance : APC and it’s documentation
Hope this helps make things more clear 🙂
Related Solutions
Python – the difference between old style and new style classes in Python
Up to Python 2.1, old-style classes were the only flavour available to the user.
The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x , but type(x) is always .
This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.
New-style classes were introduced in Python 2.2 to unify the concepts of class and type. A new-style class is simply a user-defined type, no more, no less.
If x is an instance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.__class__ ).
The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model.
It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of «descriptors», which enable computed properties.
For compatibility reasons, classes are still old-style by default.
New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the «top-level type» object if no other parent is needed.
The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns.
Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are «fixes» that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.
Python 3 only has new-style classes.
No matter if you subclass from object or not, classes are new-style in Python 3.
Python – Does Python have “private” variables in classes
It’s cultural. In Python, you don’t write to other classes’ instance or class variables. In Java, nothing prevents you from doing the same if you really want to — after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.
If you want to emulate private variables for some reason, you can always use the __ prefix from PEP 8. Python mangles the names of variables like __foo so that they’re not easily visible to code outside the class that contains them (although you can get around it if you’re determined enough, just like you can get around Java’s protections if you work at it).
By the same convention, the _ prefix means stay away even if you’re not technically prevented from doing so. You don’t play around with another class’s variables that look like __foo or _bar .
Related Question
Php built in class
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 ()
);