__serialize ක්‍රමය

මැජික් ක්‍රමය __serialize අනුක්‍රමණය කිරීමේදී ක්‍රියාත්මක වේ ශ්‍රිතය serialize මගින් වස්තුවක්. එය දත්ත අරාවක් ආපසු ලබා දිය යුතුය, අනුක්‍රමණය කරනු ඇත. මෙම ක්‍රමය PHP 7.4 හි දිස්විය ක්‍රමයට විකල්පයක් ලෙස __sleep වඩාත් නම්‍යශීලී කළමනාකරණය සමඟ අනුක්‍රමණය කිරීමේ ක්‍රියාවලිය.

වාක්‍ය රචනා ක්‍රමය

phppublic function __serialize(): array

උදාහරණය

ක්‍රමය සමඟ පන්තියක් නිර්මාණය කරමු __serialize, එය තීරණය කරනු ඇත, වස්තුවේ ගුණාංග අනුක්‍රමණය කළ යුතු බව:

php<?php
class User {
  public $name;
  private $password;
  public $email;
  
  public function __construct($name, $password, $email) {
    $this->name = $name;
    $this->password = $password;
    $this->email = $email;
  }
  
  public function __serialize(): array {
    return [
      'name' => $this->name,
      'email' => $this->email,
      'hash' => md5($this->password)
    ];
  }
}

$user = new User('John', 'secret123', 'john@example.com');
echo serialize($user);
?>

කේතය ක්‍රියාත්මක කිරීමේ ප්‍රතිඵලය:

php'O:4:"User":3:{s:4:"name";s:4:"John";s:5:"email";s:15:"john@example.com";s:4:"hash";s:32:"e5e9fa1ba31ecd1ae84f75caaa474f3a";}'

උදාහරණය

වෙනස __serialize සහ __sleep අතර පෙන්වන්න:

php<?php
class Product {
  public $id;
  protected $price;
  private $discount;
  
  public function __sleep() {
    return ['id', 'price'];
  }
  
  public function __serialize(): array {
    return [
      'id' => $this->id,
      'price' => $this->price * (1 - $this->discount)
    ];
  }
}

$product = new Product();
$product->id = 100;
$product->price = 50;
$product->discount = 0.1;

echo "Sleep: " . serialize($product) . "\n";
echo "Serialize: " . serialize($product);
?>

කේතය ක්‍රියාත්මක කිරීමේ ප්‍රතිඵලය:

php'Sleep: O:7:"Product":2:{s:2:"id";i:100;s:5:"price";i:50;}'
'Serialize: O:7:"Product":2:{s:2:"id";i:100;s:5:"price";d:45;}'

මෙයත් බලන්න

  • ශ්‍රිතය serialize,
    යම් අගයක් ගබඩා කළ හැකි වින්‍යාසයකට පරිවර්තනය කරයි