-
Notifications
You must be signed in to change notification settings - Fork 159
Files and Streams
Dmitriy Zayceff edited this page Sep 11, 2015
·
11 revisions
Zend PHP has a few functions for working with files (or streams), these are named like in the C language: fopen
, fclose
, fwrite
, etc. JPHP does not implement these functions. You should use an alternative approach in JPHP - php\io\Stream
class and its chlidren.
use php\io\Stream;
use php\io\FileStream;
$stream = Stream::of('path/to/file', 'r');
// or
$stream = new FileStream('path/to/file', 'r');
try {
$str = $stream->read(10);
// or read fully
$str = $stream->readFully();
} finally {
$stream->close();
}
// instead of ...
$fp = fopen('path/to/file', 'r');
$str = fread($fp, 10);
fclose($fp);
You still can use util class methods of Stream:
$str = Stream::getContents('path/to/file');
// instead of
$str = file_get_contents('path/to/tile');
-
file_get_contents
->Stream::getContents
-
file_put_contents
->Stream::putContents
-
file_exists
->Stream::exists
, works with not only files or usephp\io\File::exists
for files only -
fopen, fclose, fwrite, fread, fseek, etc.
->Stream
classes
The Stream class is an abstract class which has a few util methods and child classes:
-
php\io\FileStream
- for files,file://
protocol -
php\io\ResourceStream
- for resources (classpath),res://
protocol -
php\io\MemoryStream
- for memory streams,php://memory
-
php\io\MiscStream
-php://
protocols like in Zend PHP -
php\net\NetStream
- for http and ftp streams,http://
,https://
andftp://
protocols
How to include a stream?
Yes, it's supported by default, you can do like in the next example:
include "res://MyClass.php";
include "file://....";
// you cannot use external resources as http, ftp
// it will not work
include "http://...";
To work with files and directories in JPHP you can use the php\io\File
class:
use php\io\File;
$file = new File('path/to/file');
$file->isFile(); // instead of is_file
$file->isDirectory(); // instead of is_dir
...
-
file_exists
->File::exists
-
is_executable
->File::isExecutable
-
is_writable
->File::isWritable
-
is_readable
->File::isReadable
-
basename
->File::getName
-
pathinfo
->File::getAbsolutePath
,File::getCanonicalPath
,File::getPath
,File::getParent
-
mkdir
->File::mkdir
,File::mkdirs
-
???
->File::isHidden
-
???
->File::isAbsolute
-
unlink
->File::delete
,File::deleteOnExit
-
???
->File::createNewFile
-
filemtime
->File::lastModified
in millis -
filesize
->File::length
-
move
->File::renameTo
-
glob
->File::find
,File::findFiles
-
tmpfile
->File::createTemp
-
chmod
->File::setExecutable
,File::setWritable
,File::setReadable
JPHP Group 2015