PEAR is archived and read-only

This mirror preserves historical PEAR package releases and metadata so existing references remain available.

Home » Streams » Stream_Var » Manual

Allows stream based access to variables.

Introduction

Introduction – Introduction to Stream_Var

Introduction to Stream_Var

Stream_Var supplies a class that can be used as a wrapper for PHP's stream functions. This allows you to access variables with fopen(), fclose(), fwrite(), fread(), opendir() and all other filesystem functions.

You may use stream_wrapper_register() to register Stream_Var as a wrapper.

Scalar variables (strings, integers, floats) are treated as files, while arrays represent directories.

Please see the PHP Manual or the example for more information on how to register streams.

Usage scenario

Stream_Var could be used in various scenarios. Imagine you are using a class that reads data from a file but you are creating the data on-the-fly and do not want to save the data before it can be processed by the class.

This is where Stream_Var can be used. Just register it as a wrapper for fopen() and pass var://GLOBAL/yourVar as a parameter to the class.

It will read from the variable as if it was a file.

Example

Example – Example for the usage of Stream_Var

Registering the wrapper

The following example shows you how to register Stream_Var as a wrapper for the stream functions.

Registering Stream_Var

<?php
require_once "Stream/Var.php";
stream_wrapper_register( "var", "Stream_Var" );
?>

Accessing scalar variables

The following example show you how to access scalar variables with fopen(), fread(), frwite() and fclose().

Accessing scalar variables

<?php
require_once "Stream/Var.php";
stream_wrapper_register( "var", "Stream_Var" );
$foo = "I really like tomatoes.";

echo "Content of foo: $foo<br />";

$fp = fopen('var://GLOBALS/foo','r+');

$data = fread($fp, 9);
echo "Read from stream: $data<br />";

fwrite($fp,"hate");
   
fclose($fp);

echo "Content of foo: $foo<br />";
?>

Accessing an array

The following example shows how to use opendir() to access an array.

Accessing an array

<?php
require_once "Stream/Var.php";
stream_wrapper_register( "var", "Stream_Var" );
$dirname = 'var://_SERVER';
$dir = opendir($dirname);
echo    "<strong>opening directory '$dirname'</strong><br><br>";

while ($entry = readdir($dir)) {
    echo "opening file $dirname/$entry<br />";
    if (!$fp = @fopen($dirname."/".$entry,"r")) {
        echo "seems to be a directory<br /><br />";
        continue;
    }
       
    echo "reading from $entry<br />";
    while (!feof($fp)) {
        echo fread($fp, 16);
    }
    fclose($fp);
    echo    "<br /><br />";
}
closedir($dir);
?>

More examples

If you want to take a look at some more examples, just install the package and they will be installed in the docs directory.