Learning Objectives – after this chapter you will be able to:
- Inspect classes and objects at run time with
class_exists(),get_class_methods(),get_object_vars()and related functions. - Call functions dynamically with
call_user_func()and handle variable argument lists. - Work with directories – create, read, list and remove them.
- Use the file-information and file-manipulation functions of PHP.
Class and Object Functions
| Function | Purpose |
|---|---|
| class_exists(class_name [, autoload]) | Checks whether a class has been defined. |
| interface_exists(name) / trait_exists(name) | Checks whether an interface / trait has been defined. |
| method_exists(object_or_class, method) | Checks whether a method exists in a class. |
| property_exists(object_or_class, property) | Checks whether a property exists. |
| get_class(object) | Returns the name of the object's class. |
| get_parent_class(object_or_class) | Returns the name of the parent class. |
| get_class_methods(class_name) | Returns the method names of a class as an array. |
| get_class_vars(class_name) | Returns the default properties of a class as an array. |
| get_object_vars(object) | Returns the accessible properties of an object and their values. |
| get_declared_classes() | Returns an array of all defined classes. |
| get_declared_interfaces() | Returns an array of all declared interfaces. |
| is_a(object, class_name [, allow_string]) | Checks whether the object is of this class or has it as a parent. |
| is_subclass_of(object, class_name) | Checks whether the object has this class as one of its parents. |
<?php
class Person
{
public $name = "unknown";
public $city = "Bhopal";
protected $salary = 0;
public function greet() { return "Hello"; }
public function walk() {}
}
class Teacher extends Person
{
public $subject = "PHP";
public function teach() {}
}
$t = new Teacher();
echo "class_exists('Teacher'): " . var_export(class_exists('Teacher'), true) . "<br>";
echo "get_class: " . get_class($t) . "<br>";
echo "get_parent_class: " . get_parent_class($t) . "<br>";
echo "get_class_methods: " . implode(", ", get_class_methods('Teacher')) . "<br>";
echo "get_class_vars: " . implode(", ", array_keys(get_class_vars('Teacher'))) . "<br>";
echo "get_object_vars: " . json_encode(get_object_vars($t)) . "<br>";
echo "method_exists(teach): " . var_export(method_exists($t, 'teach'), true) . "<br>";
echo "is_a(Person): " . var_export(is_a($t, 'Person'), true) . "<br>";
echo "is_subclass_of(Person): " . var_export(is_subclass_of($t, 'Person'), true) . "<br>";
echo "Number of declared classes: " . count(get_declared_classes());
?>class_exists('Teacher'): true
get_class: Teacher
get_parent_class: Person
get_class_methods: teach, greet, walk
get_class_vars: subject, name, city
get_object_vars: {"name":"unknown","city":"Bhopal","subject":"PHP"}
method_exists(teach): true
is_a(Person): true
is_subclass_of(Person): true
Number of declared classes: 234Function Handling Functions
| Function | Purpose |
|---|---|
| call_user_func(callback [, args...]) | Calls a function (or method) given by name or callable. |
| call_user_func_array(callback, args_array) | Calls a function with its parameters given as an array. |
| func_get_arg(n) | Returns argument number n of the current function's argument list. |
| func_get_args() | Returns all arguments of the current function as an array. |
| func_num_args() | Returns the number of arguments passed to the current function. |
| function_exists(name) | Checks whether a function has been defined. |
| get_defined_functions() | Returns all defined functions (internal and user lists). |
| is_callable(value) | Checks whether a value can be called as a function. |
| register_shutdown_function(callback) | Registers a function to be executed when the script finishes. |
| register_tick_function(callback) / unregister_tick_function(callback) | Registers / removes a function executed on every "tick" (used with declare(ticks=N)). |
| create_function(args, code) | Created an anonymous function from strings – removed in PHP 8.0; use function () {} or fn. |
<?php
function addAll()
{
$n = func_num_args();
$args = func_get_args();
return "$n arguments, first = " . func_get_arg(0) . ", sum = " . array_sum($args);
}
function welcome($name, $city) { return "Welcome $name from $city"; }
echo addAll(5, 10, 15) . "<br>";
echo call_user_func('welcome', 'Asha', 'Indore') . "<br>";
echo call_user_func_array('welcome', ['Ravi', 'Bhopal']) . "<br>";
echo "function_exists('welcome'): " . var_export(function_exists('welcome'), true) . "<br>";
echo "is_callable('strtoupper'): " . var_export(is_callable('strtoupper'), true) . "<br>";
$user = get_defined_functions()['user'];
echo "User-defined functions: " . implode(", ", $user) . "<br>";
register_shutdown_function(function () {
echo "Shutdown function: script finished.";
});
echo "Last line of the script.<br>";
?>3 arguments, first = 5, sum = 30
Welcome Asha from Indore
Welcome Ravi from Bhopal
function_exists('welcome'): true
is_callable('strtoupper'): true
User-defined functions: addall, welcome
Last line of the script.
Shutdown function: script finished.Directory Functions
| Function | Purpose |
|---|---|
| mkdir(path [, mode, recursive]) | Creates a directory (with recursive = true, also missing parents). |
| rmdir(path) | Removes an (empty) directory. |
| is_dir(path) | Checks whether the path is a directory. |
| opendir(path) / readdir(handle) / closedir(handle) | Opens a directory, reads the next entry, closes it. |
| rewinddir(handle) | Resets the directory handle to the first entry. |
| scandir(path [, order]) | Lists files and directories of a path as an array. |
| glob(pattern [, flags]) | Finds path names matching a pattern such as *.txt. |
| dir(path) | Returns a Directory object for the path. |
| getcwd() / chdir(path) | Gets / changes the current working directory. |
| chroot(path) | Changes the root directory – only in CLI/CGI on Unix, not under Apache. |
| disk_free_space(dir) / disk_total_space(dir) | Free / total bytes on the file system. diskfreespace() is an alias. |
<?php
mkdir("reports/2026/oct", 0777, true); // recursive
file_put_contents("reports/2026/oct/sales.txt", "Sales: 1200");
file_put_contents("reports/2026/oct/stock.txt", "Stock: 340");
file_put_contents("reports/2026/summary.csv", "month,total");
echo "scandir('reports/2026'): " . implode(", ", scandir("reports/2026")) . "<br>";
echo "glob('reports/2026/oct/*.txt'): " . implode(", ", glob("reports/2026/oct/*.txt")) . "<br>";
$h = opendir("reports/2026/oct");
echo "readdir: ";
while (($entry = readdir($h)) !== false) {
if ($entry != "." && $entry != "..") echo "$entry ";
}
closedir($h);
echo "<br>is_dir('reports'): " . var_export(is_dir("reports"), true) . "<br>";
echo "Current directory: " . basename(getcwd()) . "<br>";
echo "Free disk space: " . round(disk_free_space(".") / 1073741824, 1) . " GB<br>";
// clean up: files first, then directories
array_map('unlink', glob("reports/2026/oct/*.txt"));
unlink("reports/2026/summary.csv");
rmdir("reports/2026/oct"); rmdir("reports/2026"); rmdir("reports");
echo "After cleanup, is_dir('reports'): " . var_export(is_dir("reports"), true);
?>scandir('reports/2026'): ., .., oct, summary.csv
glob('reports/2026/oct/*.txt'): reports/2026/oct/sales.txt, reports/2026/oct/stock.txt
readdir: stock.txt sales.txt
is_dir('reports'): true
Current directory: ch25
Free disk space: 29.1 GB
After cleanup, is_dir('reports'): falseFile Functions
| Function | Purpose |
|---|---|
| fopen(filename, mode) / fclose(handle) | Opens / closes a file (Chapter 14). |
| fread(handle, length) | Reads up to length bytes. |
| fgets(handle [, length]) | Reads one line (up to length-1 bytes). |
| fgetc(handle) | Reads one character. |
| fgetcsv(handle [, length, separator]) | Reads one line and parses it as CSV fields. |
| fputcsv(handle, fields [, separator]) | Writes an array as a CSV line. |
| fwrite(handle, string [, length]) | Writes to a file. fputs() is an alias. |
| fscanf(handle, format, vars...) | Parses input from a file according to a format. |
| fpassthru(handle) | Outputs all remaining data from the file pointer. |
| feof(handle) | Checks for end of file. |
| fflush(handle) | Flushes buffered output to the file. |
| fseek(handle, offset [, whence]) / ftell(handle) / rewind(handle) | Moves the pointer / tells its position / moves it to the start. |
| ftruncate(handle, size) | Truncates the file to the given size. |
| flock(handle, operation) | Locks or unlocks a file (LOCK_SH, LOCK_EX, LOCK_UN). |
| fstat(handle) / stat(filename) | Returns information (size, times …) about an open file / a file. |
| file(filename [, flags]) | Reads the whole file into an array of lines. |
| file_get_contents(filename) / file_put_contents(filename, data) | Reads / writes a whole file in one call. |
| readfile(filename) | Reads a file and writes it to the output. |
| file_exists(filename) | Checks whether a file or directory exists. |
| is_file / is_readable / is_writable / is_executable / is_link (filename) | Checks the type or permission of a file. |
| is_uploaded_file(filename) / move_uploaded_file(from, to) | Checks / moves a file uploaded with HTTP POST. |
| filesize(filename) | Returns the file size in bytes. |
| filetype(filename) | Returns the type: file, dir, link … |
| filemtime / fileatime / filectime (filename) | Last modification / access / inode-change time (timestamp). |
| fileperms / fileowner / filegroup / fileinode (filename) | Permissions, owner, group and inode of the file. |
| copy(from, to) / rename(old, new) / unlink(filename) | Copies / renames (moves) / deletes a file. |
| tempnam(dir, prefix) / tmpfile() | Creates a unique temporary file name / a temporary file. |
| touch(filename [, time]) | Sets the modification time (creates the file if needed). |
| chmod / chown / chgrp (filename, value) | Changes permissions / owner / group. |
| basename(path) / dirname(path) / pathinfo(path) / realpath(path) | Parts of a path; absolute path. |
| fnmatch(pattern, filename) | Checks whether a file name matches a shell wildcard pattern. |
| parse_ini_file(filename [, sections]) | Parses a configuration (.ini) file into an array. |
| link / symlink / readlink / linkinfo | Creates hard/symbolic links and reads link information. |
| umask([mask]) / clearstatcache() | Changes the umask / clears the file-status cache. |
| popen(command, mode) / pclose(handle) | Opens / closes a pipe to a process. |
| fgetss(handle) | Read a line and stripped HTML tags – removed in PHP 8.0; use strip_tags(fgets(...)). |
<?php
file_put_contents("students.csv", "roll,name,city\n101,Asha,Bhopal\n102,Ravi,Indore\n");
$path = "/opt/lampp/htdocs/phpbook/ch25/students.csv";
echo "basename: " . basename($path) . "<br>";
echo "dirname: " . dirname($path) . "<br>";
echo "pathinfo extension: " . pathinfo($path, PATHINFO_EXTENSION) . "<br>";
echo "filesize: " . filesize("students.csv") . " bytes, filetype: " . filetype("students.csv") . "<br>";
echo "is_readable: " . var_export(is_readable("students.csv"), true) . "<br>";
echo "permissions: " . substr(sprintf('%o', fileperms("students.csv")), -4) . "<br>";
echo "fnmatch('*.csv'): " . var_export(fnmatch("*.csv", "students.csv"), true) . "<br>";
$h = fopen("students.csv", "r");
$header = fgetcsv($h);
echo "<b>" . implode(" | ", $header) . "</b><br>";
while (($row = fgetcsv($h)) !== false) {
echo implode(" | ", $row) . "<br>";
}
echo "Pointer position at end: " . ftell($h) . "<br>";
rewind($h);
echo "After rewind: " . ftell($h) . "<br>";
fclose($h);
file_put_contents("settings.ini", "[database]\nhost = localhost\nuser = root\n[site]\ntitle = PHP Book\n");
$ini = parse_ini_file("settings.ini", true);
echo "parse_ini_file: host = {$ini['database']['host']}, title = {$ini['site']['title']}";
?>basename: students.csv
dirname: /opt/lampp/htdocs/phpbook/ch25
pathinfo extension: csv
filesize: 47 bytes, filetype: file
is_readable: true
permissions: 0644
fnmatch('*.csv'): true
roll | name | city
101 | Asha | Bhopal
102 | Ravi | Indore
Pointer position at end: 47
After rewind: 0
parse_ini_file: host = localhost, title = PHP BookKey Takeaways
- Class/object functions (
class_exists,get_class_methods,get_object_vars,is_a…) inspect code at run time. call_user_func()/call_user_func_array()call functions dynamically;func_get_args()reads variable arguments;create_function()is gone in PHP 8.- Directories:
mkdir,rmdir,scandir,glob,opendir/readdir/closedir,is_dir. - Files: open/read/write functions, CSV helpers
fgetcsv/fputcsv, information functions (filesize,filemtime,pathinfo…) andcopy/rename/unlink. fgetss()was removed in PHP 8 – combinefgets()andstrip_tags().
Program File
Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch25 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.
Question / Answer (15 questions)
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.
- The PHP Group. (n.d.). PHP Manual – Class/Object Functions. https://www.php.net/manual/en/ref.classobj.php
- The PHP Group. (n.d.). PHP Manual – Function handling Functions. https://www.php.net/manual/en/ref.funchand.php
- The PHP Group. (n.d.). PHP Manual – Directory Functions. https://www.php.net/manual/en/ref.dir.php
- The PHP Group. (n.d.). PHP Manual – Filesystem Functions. https://www.php.net/manual/en/ref.filesystem.php