2013-03-11 48 views
2

在此段後面的代碼片段中,我使用Test_Stream對象創建了一個名爲test的流封裝器。我正在嘗試使用流上下文,並有幾個問題。首先這裏是代碼:自定義流封裝的流上下文

<?php 
class Test_Stream { 
    public $context; 

    public function __construct() 
    { 
     print_r(stream_context_get_options($this->context)); 
     exit; 
    } 
} 

$context = array(
    'test' => array('key' => 'value'), 
    'otherwrapper' => array('key' =>'value') 
); 
$context = stream_context_create($context); 

stream_wrapper_register('test', 'Test_Stream'); 

$fp = fopen('test://www.domain.tld/whatever', 'r', false, $context); 

所以現在,在該代碼片斷,Test_Stream被註冊到「測試」流包裝,但是......如果我不事先知道包裝的名字將如果我想讓它由開發人員來決定,那麼我該怎麼做呢?你怎麼知道班上的包裝名字是什麼?好像你必須事先知道它以獲得適當的上下文選項(除非你只假定第一個上下文選項數組是正確的),但如果你不提前知道它會怎麼樣?

回答

1

你知道開放的協議是所謂的,所以,有使用情境:

<?php 
class Test_Stream { 
    public $context; 

    public function stream_open($path, $mode, $options, &$opened_path){ 
     var_dump(parse_url($path, PHP_URL_SCHEME)); 
     exit; 
    } 
} 

$context = array(
    'test' => array('key' => 'value'), 
    'otherwrapper' => array('key' =>'value') 
); 
$context = stream_context_create($context); 
stream_wrapper_register('test', 'Test_Stream'); 
$fp = fopen('test://www.domain.tld/whatever', 'r', false, $context); 


string(4) "test"