PHP.mk документација

Серијализација на објекти

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

language.oop5.serialization.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека language.oop5.serialization.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
Серијализација на објекти

Референца за `language.oop5.serialization.php` со подобрена типографија и навигација.

language.oop5.serialization.php

Серијализирање објекти - објекти во сесии

serialize() враќа стринг што содржи бајт-стрим репрезентација на која било вредност што може да се чува во PHP. unserialize() може да го користи овој стринг за да ги рекреира оригиналните вредности на променливите. Користењето serialize за зачувување на објект ќе ги зачува сите променливи во објект. Методите во објект нема да бидат зачувани, само името на класата.

За да може unserialize() an object, the class of that object needs to be defined. That is, if you have an object of class A and serialize this, you'll get a string that refers to class A and contains all values of variables contained in it. If you want to be able to unserialize an object of class A in another file, the definition of class A must be present in that file first. This can be done for example by storing the class definition of class A in an include file and including this file or making use of the spl_autoload_register() function.

<?php
// A.php:
  
  class A {
      public $one = 1;
    
      public function show_one() {
          echo $this->one;
      }
  }
  
// page1.php:

  include "A.php";
  
  $a = new A;
  $s = serialize($a);
  // store $s somewhere where page2.php can find it.
  file_put_contents('store', $s);

// page2.php:
  
  // this is needed for the unserialize to work properly.
  include "A.php";

  $s = file_get_contents('store');
  $a = unserialize($s);

  // now use the function show_one() of the $a object.  
  $a->show_one();
?>

It is strongly recommended that if an application serializes objects, for use later in the application, the application includes the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of __PHP_Incomplete_Class_Name, која нема методи и би го направила објектот бескорисен.

Значи, ако во горниот пример $a стана дел од сесија со додавање нов клуч на $_SESSION суперглобалната низа, треба да ја вклучите датотеката A.php на сите ваши страници, не само page1.php and page2.php.

Покрај горенаведениот совет, имајте предвид дека можете исто така да се поврзете на настаните за серијализирање и десеријализирање на објект користејќи ги __sleep() and __wakeup() методи. Користење __sleep() исто така ви овозможува да серијализирате само подмножество од својствата на објектот.

Белешки од корисници 3 белешки

php на lanar точка com точка au
пред 16 години
Note that static members of an object are not serialized.
michael на smith-li точка com
пред 11 години
Reading this page you'd be left with the impression that a class's `serialize` and `unserialize` methods are unrelated to the `serialize` and `unserialize` core functions; that only `__sleep` and `__unsleep` allow you to customize an object's serialization interface. But look at http://php.net/manual/en/class.serializable.php and you'll see that there is a more straightforward way to control how a user-defined object is serialized and unserialized.
Анонимен
пред 5 години
Until such time as these documents are updated, note that `session_register()` is not needed to automatically serialize & unserialize objects in sessions. Any objects in `$_SESSION` are serialized when the session is closed (via `session_write_close()` or upon script exit) & unserialized when opened (via `session_start()`). The note about including classes throughout an app (either by including the definition globally or autoloading it) still holds.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.