Php class name in function parameter

Php class name in function parameter

By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string .

It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float . Function calls from within internal functions will not be affected by the strict_types declaration.

To enable strict mode, the declare statement is used with the strict_types declaration:

Enabling strict mode will also affect return type declarations.

Note:

Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller’s preference (weak typing) will be respected, and the value will be coerced.

Note:

Strict typing is only defined for scalar type declarations, and as such, requires PHP 7.0.0 or later, as scalar type declarations were added in that version.

Example #11 Strict typing

function sum ( int $a , int $b ) return $a + $b ;
>

var_dump ( sum ( 1 , 2 ));
var_dump ( sum ( 1.5 , 2.5 ));
?>

The above example will output:

int(3) Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 9 and defined in -:4 Stack trace: #0 -(9): sum(1.5, 2.5) #1 thrown in - on line 4

Example #12 Weak typing

function sum ( int $a , int $b ) return $a + $b ;
>

// These will be coerced to integers: note the output below!
var_dump ( sum ( 1.5 , 2.5 ));
?>

The above example will output:

Example #13 Catching TypeError

function sum ( int $a , int $b ) return $a + $b ;
>

try var_dump ( sum ( 1 , 2 ));
var_dump ( sum ( 1.5 , 2.5 ));
> catch ( TypeError $e ) echo ‘Error: ‘ . $e -> getMessage ();
>
?>

The above example will output:

int(3) Error: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 10

Variable-length argument lists

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the . token in PHP 5.6 and later, and using the func_num_args() , func_get_arg() , and func_get_args() functions in PHP 5.5 and earlier.

. in PHP 5.6+

In PHP 5.6 and later, argument lists may include the . token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

Читайте также:  Php скрипт генерации страницы

Example #14 Using . to access variable arguments

function sum (. $numbers ) $acc = 0 ;
foreach ( $numbers as $n ) $acc += $n ;
>
return $acc ;
>

The above example will output:

You can also use . when calling functions to unpack an array or Traversable variable or literal into the argument list:

Example #15 Using . to provide arguments

The above example will output:

You may specify normal positional arguments before the . token. In this case, only the trailing arguments that don’t match a positional argument will be added to the array generated by . .

It is also possible to add a type hint before the . token. If this is present, then all arguments captured by . must be objects of the hinted class.

Example #16 Type hinted variable arguments

function total_intervals ( $unit , DateInterval . $intervals ) $time = 0 ;
foreach ( $intervals as $interval ) $time += $interval -> $unit ;
>
return $time ;
>

$a = new DateInterval ( ‘P1D’ );
$b = new DateInterval ( ‘P2D’ );
echo total_intervals ( ‘d’ , $a , $b ). ‘ days’ ;

// This will fail, since null isn’t a DateInterval object.
echo total_intervals ( ‘d’ , null );
?>

The above example will output:

3 days Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2

Finally, you may also pass variable arguments by reference by prefixing the . with an ampersand ( & ).

Older versions of PHP

No special syntax is required to note that a function is variadic; however access to the function’s arguments must use func_num_args() , func_get_arg() and func_get_args() .

The first example above would be implemented as follows in PHP 5.5 and earlier:

Example #17 Accessing variable arguments in PHP 5.5 and earlier

function sum () $acc = 0 ;
foreach ( func_get_args () as $n ) $acc += $n ;
>
return $acc ;
>

The above example will output:

Источник

Php class name in function parameter

To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.

#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>

$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );

$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;

/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us

3 valuue yes 129 s
4 reference yes 66 us

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)

Читайте также:  Php get all countries

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>

Источник

Get Class Name in PHP

Get Class Name in PHP

  1. Use Class Name Resolution to Get Class Name in PHP
  2. Use __CLASS__ Constant to Get Class Name in PHP
  3. Use get_class() Function to Get Class Name in PHP
  4. Use Reflection Class to Get Class Name in PHP
  5. Use ::class on Object to Get Class Name in PHP

This tutorial will discuss how to get a PHP class name with class name resolution, PHP __CLASS__ constant, and the get_class() method. You will learn its usage for the class name resolution in and out of a class.

Use Class Name Resolution to Get Class Name in PHP

You can get a class name via class name resolution when you have a namespace in your code. The result is a Fully Qualified Class Name (FQCN).

This feature is available in PHP as ClassName::class . It is useful when you have a namespace in your PHP.

In the following code example, the class name resolution via ClassName::class will return the class name of the associated class:

php  namespace YourNameSpace;   // Define a class  class HelloClassName <>   // Get the class name from ::class  echo HelloClassName::class; ?> 
YourNameSpace\HelloClassName 

If you want to use this feature in a class method, you can get the class name via the static method. You’ll write this as static::class .

The next code example shows how to get a class name in a class method.

php  namespace YourNameSpace;   // Define the class name  class HelloClassName   /**  * Define a function that returns  * the class name via static::class  */  public function getClassName()   return static::class;  >  >   // Create a new object  $hello_class_name = new HelloClassName();   // Get the class name  echo $hello_class_name->getClassName(); ?> 
YourNameSpace\HelloClassName 

Use __CLASS__ Constant to Get Class Name in PHP

The __CLASS__ constant is part of the PHP predefined constant. You can use it within a class to get a class name.

The following code will get the class name via the __CLASS__ constant.

php  // Define the class  class Hello   // This function will return the  // class name  function HelloName ()  return __CLASS__;  >  >   // Create a new object  $hello_object= new Hello();   // Get the class name  echo $hello_object->HelloName(); ?> 

Use get_class() Function to Get Class Name in PHP

PHP provides a get_class() function. This function will return the class name. You can use it in procedural and object-oriented programming. First, we’ll take a look at the procedural style.

The next code block defines a class with a single function. The function within the class will return the class name when its argument is the this keyword.

To get the class name, you create an object from the class; then, you pass the object’s name to get_class() .

php  // Define a class  class Hello   function class_name()   echo "The class name is: ", get_class($this);  >  >   // Create a new object  $new_hello_object = new Hello();   // Get the class name  $new_hello_object->class_name();   // Also, you can get the class name  // via an external call  // echo get_class($new_hello_object);  ?> 

At first, for the OOP style, you can return the get_class() function from a static class.

php  // Define a class  class Hello   public static function class_name()   return get_class();  >  >   // Get the class name  $class_name = Hello::class_name();   echo $class_name; ?> 

This method has its limitations because when you extend the class, the extended class will return the name of the parent class and not the extended class. To solve this, you can use get_called_class() .

The get_called class() function relies on Late Static Binding. With this function, PHP will return the name of the calling class. It solves the situation where the extended class returns the name of its parent class rather than its own.

php  // Define a class  class Hello    // A static function that returns the  // name of the class that calls it  public static function called_class_name()   return get_called_class();  >   // This function will return the  // defining class name  public static function get_defining_class()   return get_class();  > >  class ExtendHello extends Hello   >  $hello_class_name = Hello::called_class_name(); $extended_class_name = ExtendHello::called_class_name(); $extend_hello_parent_class = ExtendHello::get_defining_class();  echo "Hello class name: " . $hello_class_name . "\n"; echo "Extended Hello class name: " . $extended_class_name . "\n"; echo "Extended Hello parent class name: " . $extend_hello_parent_class . "\n"; ?> 
Hello class name: Hello Extended Hello class name: ExtendHello Extended Hello parent class name: Hello 

Use Reflection Class to Get Class Name in PHP

Reflection Class is a concise way to get a class name in PHP. You create a class; within this class, create a function that returns a new Reflection class.

The Reflection class should have its argument set to $this . Afterward, you can get the class name via the getShortName() method available with the Reflection class.

php  // Define a class  class Hello   // A function that returns the class  // name via reflection  public function HelloClassName()   return (new \ReflectionClass($this))->getShortName();  >  >   // Create a new class name  $hello_class_name = new Hello();   // Get the class name  echo $hello_class_name->HelloClassName(); ?> 

Use ::class on Object to Get Class Name in PHP

The ::class feature worked on classes before PHP 8. Since PHP, when you create an object from a class, you can get the class name from the created object with ::class .

You’ll find an example in the following code block.

php  namespace YourNameSpace;   // define the class  class HelloClassName    >   // Create a new object  $hello_class_name = new HelloClassName();   // Get the class name from the object  // via ::class  echo $hello_class_name::class; ?> 
YourNameSpace\HelloClassName 

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

Related Article — PHP Class

Источник

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