PHP code example of ali-eltaweel / lazy-props

1. Go to this page and download the library: Download ali-eltaweel/lazy-props library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ali-eltaweel / lazy-props example snippets


use Lang\{ Annotations\LazyInitialized, LazyProperties };

class Database {

  use LazyProperties;

  #[LazyInitialized('createConnection')]
  public $connection;

  function createConnection() {
        
    return new stdClass();
  }
}

class X {
  
  use LazyProperties;

  #[LazyInitialized('createArgument')]
  public int $x;
  
  #[LazyInitialized('createArgument')]
  public int $y;

  private function createArgument(string $name): int {
      
    echo "Initializing {$name}...\n";
    
    return match ($name) {
      'x' => 42,
      'y' => 84,
    };
  }
}

#[InitializerMethod('createArgument')]
class X {

  #[LazyInitialized()]
  public int $x;
  
  #[LazyInitialized()]
  public int $y;
}

class X {

  use LazyProperties;

  #[LazyInitialized('getX')]
  public int $x;

  private function getX() {
      
    return 42;
  }
}

class Y extends X {

  #[LazyInitialized('getY')]
  public int $y;

  // you can't make this initializer private, because it is called from the parent class.
  protected function getY() {
    
    echo "Initializing y...\n";
    return 84;
  }
}

$y = new Y();

var_dump($y->y);
var_dump($y->y);
// "Initializing y..." is printed only once

class Y extends X {

  #[LazyInitialized('getY')]
  public readonly int $y;
}

use Lang\{ Annotations\ExtendedLazyProperties, LazyPropertiesExtension };

#[ExtendedLazyProperties('y')]
class Y extends X {

  use LazyPropertiesExtension;

  #[LazyInitialized('getY')]
  public readonly int $y;
}

#[ExtendedLazyProperties('z')]
class Z extends Y {

  use LazyPropertiesExtension;

  #[LazyInitialized('getZ')]
  public readonly int $z;
}