問題:

程式執行出現以下錯誤

Fatal error: main() [<a href='function.main'>function.main</a>]: The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition &quot;MyClass&quot; of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition in xxx.php on line 4

原因:

這是因為程式某些操作產生Incomplete Object(__PHP_Incomplete_Class),並且呼叫了此物件的函式。產生Incomplete Object的原因是序列化的資料轉回原始物件時,該物件的類別並未被定義,常見的情況如下:

利用Session存取自定義物件

例如定義一個類別

<?php
	class MyClass
	{
		function f()
		{
			echo "Test";
		}
	}
?>
<?php
	include("c.php");
	session_start();
	$c = new MyClass();
	$_SESSION['c'] = $c;
?>

在別的程序取出實例

<?php
	session_start();
	include("c.php");
	$c = $_SESSION['c'];
	$c->f();
?>

序列化與反序列化自定義物件

建立類別實例並序列化

<?php
	include("c.php");
	$c = new MyClass();
	echo serialize($c);  // O:1:"MyClass":0:{}
?>

在別的程序反序列化

<?php
	$c = unserialize('O:1:"MyClass":0:{}');
	$c->f();
	include("c.php");
?>

由於在session_start()和反序列化之前,自定義類別並未引用,造成此錯誤。

解決方案:

需引用自定義類別並且在session_start()和反序列化動作之前。

<?php
	include("c.php");
	session_start();
	$c = $_SESSION['c'];
	$c->f();
?>
<?php
	include("c.php");
	$c = unserialize('O:1:"MyClass":0:{}');
	$c->f();
?>

並確保php.ini中的session.auto_start設定停用

session.auto_start = 0

或透過.htaccess停用

php_value session.auto_start 0
文章標籤
創作者介紹

小殘的程式光廊

emn178 發表在 痞客邦 PIXNET 留言(0) 人氣()