PHP Functions 4 programs with output 15 Q/A 5 MCQs

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
FunctionPurpose
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.
File: htdocs/phpbook/ch25/classinfo.php
<?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());
?>
OUTPUT browser · http://localhost/phpbook/ch25/classinfo.php
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: 234
Function Handling Functions
FunctionPurpose
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.
File: htdocs/phpbook/ch25/funchandling.php
<?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>";
?>
OUTPUT browser · http://localhost/phpbook/ch25/funchandling.php
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
FunctionPurpose
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.
File: htdocs/phpbook/ch25/dirs.php
<?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);
?>
OUTPUT browser · http://localhost/phpbook/ch25/dirs.php
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'): false
File Functions
FunctionPurpose
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 / linkinfoCreates 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(...)).
File: htdocs/phpbook/ch25/fileinfo.php
<?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']}";
?>
OUTPUT browser · http://localhost/phpbook/ch25/fileinfo.php
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 Book
Key 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 …) and copy/rename/unlink.
  • fgetss() was removed in PHP 8 – combine fgets() and strip_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)

Answer : With class_exists("ClassName"), which returns true or false (and may trigger the autoloader).

Answer : get_class_vars() returns the default properties of a class; get_object_vars() returns the current accessible properties and values of a particular object.

Answer : An array with the names of the methods of a class (those accessible from the calling scope), including inherited ones.

Answer : is_a() is true if the object belongs to the class or has it as a parent; is_subclass_of() is true only if the class is a parent, not for the object's own class.

Answer : To call a function when its arguments are available as an array: call_user_func_array('welcome', ['Ravi', 'Bhopal']).

Answer : func_num_args() (count), func_get_arg(n) (one argument) and func_get_args() (all arguments). Modern code uses ...$args.

Answer : It registers a function that PHP executes when the script finishes, normally or after exit(), useful for logging and clean-up.

Answer : It was deprecated in 7.2 and removed in 8.0 because it used eval() internally; anonymous functions (function () {} or fn) replace it.

Answer : mkdir("a/b/c", 0777, true) – the third argument true creates missing parent directories.

Answer : scandir($dir) lists all entries (including . and ..) of one directory; glob($pattern) returns paths that match a wildcard pattern such as *.txt.

Answer : $h = opendir($dir); while (($e = readdir($h)) !== false) { … } closedir($h); – skipping the entries "." and "..".

Answer : rmdir($dir); the directory must be empty, so its files must be deleted first with unlink().

Answer : Open it with fopen() and call fgetcsv($handle) in a loop; each call returns one line as an array of fields.

Answer : basename() the file name part of a path, dirname() the directory part, and pathinfo() an array (or one part) with dirname, basename, extension and filename.

Answer : It places a shared (LOCK_SH) or exclusive (LOCK_EX) lock on a file and releases it with LOCK_UN, preventing two requests from writing the same file at the same time.
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.

Q1. Which function returns the name of an object's class?

Show Answer

Correct Answer : A. get_class()
get_class($obj) returns the class name.

Q2. Which function was removed in PHP 8.0?

Show Answer

Correct Answer : B. create_function()
create_function() was removed; use closures.

Q3. Which function lists files matching *.txt?

Show Answer

Correct Answer : B. glob()
glob() works with wildcard patterns.

Q4. rmdir() succeeds only if the directory is:

Show Answer

Correct Answer : B. Empty
Files must be removed first.

Q5. Which function parses a line of a CSV file into an array?

Show Answer

Correct Answer : B. fgetcsv()
fgetcsv() reads and parses one line from a file handle.

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.

  1. The PHP Group. (n.d.). PHP Manual – Class/Object Functions. https://www.php.net/manual/en/ref.classobj.php
  2. The PHP Group. (n.d.). PHP Manual – Function handling Functions. https://www.php.net/manual/en/ref.funchand.php
  3. The PHP Group. (n.d.). PHP Manual – Directory Functions. https://www.php.net/manual/en/ref.dir.php
  4. The PHP Group. (n.d.). PHP Manual – Filesystem Functions. https://www.php.net/manual/en/ref.filesystem.php