Php is anonymous class

Anonymous classes

Support for anonymous classes was added in PHP 7. Anonymous classes are useful when simple, one-off objects need to be created.

// Pre PHP 7 code
class Logger
public function log ( $msg )
echo $msg ;
>
>

$util -> setLogger (new Logger ());

// PHP 7+ code
$util -> setLogger (new class public function log ( $msg )
echo $msg ;
>
>);

They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:

class SomeClass <>
interface SomeInterface <>
trait SomeTrait <>

var_dump (new class( 10 ) extends SomeClass implements SomeInterface private $num ;

public function __construct ( $num )
$this -> num = $num ;
>

Результат выполнения данного примера:

object(class@anonymous)#1 (1) < ["Command line code0x104c5b612":"class@anonymous":private]=>int(10) >

Nesting an anonymous class within another class does not give it access to any private or protected methods or properties of that outer class. In order to use the outer class’ protected properties or methods, the anonymous class can extend the outer class. To use the private properties of the outer class in the anonymous class, they must be passed through its constructor:

class Outer
private $prop = 1 ;
protected $prop2 = 2 ;

protected function func1 ()
return 3 ;
>

public function func2 ()
return new class( $this -> prop ) extends Outer private $prop3 ;

public function __construct ( $prop )
$this -> prop3 = $prop ;
>

public function func3 ()
return $this -> prop2 + $this -> prop3 + $this -> func1 ();
>
>;
>
>

echo (new Outer )-> func2 ()-> func3 ();

Результат выполнения данного примера:

Источник

Php is anonymous class

Anonymous classes are useful when simple, one-off objects need to be created.

// Using an explicit class
class Logger
public function log ( $msg )
echo $msg ;
>
>

$util -> setLogger (new Logger ());

// Using an anonymous class
$util -> setLogger (new class public function log ( $msg )
echo $msg ;
>
>);

They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:

class SomeClass <>
interface SomeInterface <>
trait SomeTrait <>

var_dump (new class( 10 ) extends SomeClass implements SomeInterface private $num ;

public function __construct ( $num )
$this -> num = $num ;
>

The above example will output:

object(class@anonymous)#1 (1) < ["Command line code0x104c5b612":"class@anonymous":private]=>int(10) >

Nesting an anonymous class within another class does not give it access to any private or protected methods or properties of that outer class. In order to use the outer class’ protected properties or methods, the anonymous class can extend the outer class. To use the private properties of the outer class in the anonymous class, they must be passed through its constructor:

class Outer
private $prop = 1 ;
protected $prop2 = 2 ;

protected function func1 ()
return 3 ;
>

public function func2 ()
return new class( $this -> prop ) extends Outer private $prop3 ;

public function __construct ( $prop )
$this -> prop3 = $prop ;
>

public function func3 ()
return $this -> prop2 + $this -> prop3 + $this -> func1 ();
>
>;
>
>

echo (new Outer )-> func2 ()-> func3 ();

The above example will output:

All objects created by the same anonymous class declaration are instances of that very class.

if ( get_class ( anonymous_class ()) === get_class ( anonymous_class ())) echo ‘same class’ ;
> else echo ‘different class’ ;
>

The above example will output:

Note:

Note that anonymous classes are assigned a name by the engine, as demonstrated in the following example. This name has to be regarded an implementation detail, which should not be relied upon.

The above example will output something similar to:

class@anonymous/in/oNi1A0x7f8636ad2021

User Contributed Notes 9 notes

Below three examples describe anonymous class with very simple and basic but quite understandable example

// First way — anonymous class assigned directly to variable
$ano_class_obj = new class public $prop1 = ‘hello’ ;
public $prop2 = 754 ;
const SETT = ‘some config’ ;

public function getValue ()
// do some operation
return ‘some returned value’ ;
>

public function getValueWithArgu ( $str )
// do some operation
return ‘returned value is ‘ . $str ;
>
>;

var_dump ( $ano_class_obj );
echo «\n» ;

echo $ano_class_obj -> prop1 ;
echo «\n» ;

echo $ano_class_obj -> prop2 ;
echo «\n» ;

echo $ano_class_obj :: SETT ;
echo «\n» ;

echo $ano_class_obj -> getValue ();
echo «\n» ;

echo $ano_class_obj -> getValueWithArgu ( ‘OOP’ );
echo «\n» ;

// Second way — anonymous class assigned to variable via defined function
$ano_class_obj_with_func = ano_func ();

function ano_func ()
return new class public $prop1 = ‘hello’ ;
public $prop2 = 754 ;
const SETT = ‘some config’ ;

public function getValue ()
// do some operation
return ‘some returned value’ ;
>

public function getValueWithArgu ( $str )
// do some operation
return ‘returned value is ‘ . $str ;
>
>;
>

var_dump ( $ano_class_obj_with_func );
echo «\n» ;

echo $ano_class_obj_with_func -> prop1 ;
echo «\n» ;

echo $ano_class_obj_with_func -> prop2 ;
echo «\n» ;

echo $ano_class_obj_with_func :: SETT ;
echo «\n» ;

echo $ano_class_obj_with_func -> getValue ();
echo «\n» ;

echo $ano_class_obj_with_func -> getValueWithArgu ( ‘OOP’ );
echo «\n» ;

// Third way — passing argument to anonymous class via constructors
$arg = 1 ; // we got it by some operation
$config = [ 2 , false ]; // we got it by some operation
$ano_class_obj_with_arg = ano_func_with_arg ( $arg , $config );

function ano_func_with_arg ( $arg , $config )
return new class( $arg , $config ) public $prop1 = ‘hello’ ;
public $prop2 = 754 ;
public $prop3 , $config ;
const SETT = ‘some config’ ;

public function __construct ( $arg , $config )
$this -> prop3 = $arg ;
$this -> config = $config ;
>

public function getValue ()
// do some operation
return ‘some returned value’ ;
>

public function getValueWithArgu ( $str )
// do some operation
return ‘returned value is ‘ . $str ;
>
>;
>

var_dump ( $ano_class_obj_with_arg );
echo «\n» ;

echo $ano_class_obj_with_arg -> prop1 ;
echo «\n» ;

echo $ano_class_obj_with_arg -> prop2 ;
echo «\n» ;

echo $ano_class_obj_with_arg :: SETT ;
echo «\n» ;

echo $ano_class_obj_with_arg -> getValue ();
echo «\n» ;

echo $ano_class_obj_with_arg -> getValueWithArgu ( ‘OOP’ );
echo «\n» ;

Источник

ReflectionClass::isAnonymous

Returns true on success or false on failure.

Examples

Example #1 ReflectionClass::isAnonymous() example

class TestClass <>
$anonClass = new class <>;

$normalClass = new ReflectionClass ( ‘TestClass’ );
$anonClass = new ReflectionClass ( $anonClass );

var_dump ( $normalClass -> isAnonymous ());
var_dump ( $anonClass -> isAnonymous ());

The above example will output:

See Also

User Contributed Notes

  • ReflectionClass
    • _​_​construct
    • getAttributes
    • getConstant
    • getConstants
    • getConstructor
    • getDefaultProperties
    • getDocComment
    • getEndLine
    • getExtension
    • getExtensionName
    • getFileName
    • getInterfaceNames
    • getInterfaces
    • getMethod
    • getMethods
    • getModifiers
    • getName
    • getNamespaceName
    • getParentClass
    • getProperties
    • getProperty
    • getReflectionConstant
    • getReflectionConstants
    • getShortName
    • getStartLine
    • getStaticProperties
    • getStaticPropertyValue
    • getTraitAliases
    • getTraitNames
    • getTraits
    • hasConstant
    • hasMethod
    • hasProperty
    • implementsInterface
    • inNamespace
    • isAbstract
    • isAnonymous
    • isCloneable
    • isEnum
    • isFinal
    • isInstance
    • isInstantiable
    • isInterface
    • isInternal
    • isIterable
    • isIterateable
    • isReadOnly
    • isSubclassOf
    • isTrait
    • isUserDefined
    • newInstance
    • newInstanceArgs
    • newInstanceWithoutConstructor
    • setStaticPropertyValue
    • _​_​toString
    • export

    Источник

    PHP Anonymous Class

    Summary: in this tutorial, you’ll learn how about the PHP anonymous class and how to define anonymous classes.

    Introduction to the PHP anonymous classes

    So far, you have learned how to define a new class with a name. For example:

     class MyClass < // . >Code language: PHP (php)

    The MyClass is called a named class.

    An anonymous class is a class without a declared name. The following creates an object of anonymous class:

     $myObject = new class < // . >;Code language: PHP (php)

    In this syntax, you place the class keyword after the new keyword. The $myObject is the instance of the anonymous class.

    Inside the parentheses, you can define constructor, destructor, properties, and methods for the anonymous class like a regular class. For example:

     $logger = new class < public function log(string $message): void < echo $message . '
    '
    ; > >; $logger->log('Hello');
    Code language: PHP (php)

    First, create the $logger object of the anonymous class that has one method log() that displays a message with a
    tag.

    Second, call the log() method via the $logger object.

    Internally, PHP generates a name for the anonymous class. To get the generated name, you can use the get_class() function. For example:

    echo get_class($logger);Code language: PHP (php)
    index.php0000025F568665BECode language: PHP (php)

    PHP manages this class name internally. Therefore, you should not rely on it.

    Implementing an interface

    An anonymous can implement one or multiple interfaces. For example:

     interface Logger < public function log(string $message): void; > $logger = new class implements Logger < public function log(string $message): void < echo $message . '
    '
    ; > >; $logger->log('Hello');
    Code language: PHP (php)

    In this example, we define the Logger interface that has the log() method. And then, we define an anonymous class that implements the Logger interface.

    The $logger is the instance of the Logger interface:

    echo $logger instanceof Logger; // trueCode language: PHP (php)

    Because an anonymous doesn’t have a declared name, you cannot use the type hint for its instance.

    However, when an anonymous class implements an interface, you can use the type hint via the interface. For example:

     interface Logger < public function log(string $message): void; > $logger = new class implements Logger < public function log(string $message): void < echo $message . '
    '
    ; > >; // type hint function save(Logger $logger) < $logger->log('The file was updated successfully.'); > save($logger);
    Code language: PHP (php)

    Inheriting a class

    Like a regular class, a class can inherit from one named class. For example:

     interface Logger < public function log(string $message): void; > abstract class SimpleLogger implements Logger < protected $newLine; public function __construct(bool $newLine) < $this->newLine = $newLine; > abstract public function log(string $message): void; > $logger = new class(true) extends SimpleLogger < public function __construct(bool $newLine) < parent::__construct($newLine); > public function log(string $message): void < echo $this->newLine ? $message . PHP_EOL : $message; > >; $logger->log('Hello'); $logger->log('Bye');Code language: PHP (php)

    First, define an interface called Logger that has one method log() .

    Second, define an abstract class called SimpleLogger that implements the Logger interface.

    Third, define an anonymous class that extends the SimpleLogger class. We call the constructor of the SimpleLogger class in the constructor of the anonymous class.

    To pass an argument to the constructor, we place it in parentheses that follow the class keyword.

    Finally, call the log() method of the $logger object.

    When to use anonymous classes

    Anonymous classes are helpful in some cases:

    First, anonymous classes make it easy to mock tests. Note that you’ll learn about unit testing with PHPUnit later.

    Second, anonymous classes keep their usage outside the scope where they are defined. For example, instead of doing this:

     class ConsoleLogger < public function log($message) < echo $message . PHP_EOL; > > $obj->setLogger(new ConsoleLogger());Code language: PHP (php)

    Now, you can make use the an anonymous class like this:

    $obj->setLogger(new class < public function log($msg) < echo $message . PHP_EOL; > >);Code language: PHP (php)

    Third, make a small optimization by avoid hitting the autoloader for trivial classes.

    Summary

    Источник

    Читайте также:  Python vs node js vs php
Оцените статью