Editing php class to php 8 version

Hello,

What should be changed in the code below to make it compatible with PHP 8.2 version?

class treeview {

	private $files;
	private $folder;
	
	function __construct( $path ) {
		
		$files = array();	
		
		if( file_exists( $path)) {
			if( $path[ strlen( $path ) - 1 ] ==  '/' )
				$this->folder = $path;
			else
				$this->folder = $path . '/';
			
			$this->dir = opendir( $path );
			while(( $file = readdir( $this->dir ) ) != false )
				$this->files[] = $file;
			closedir( $this->dir );
		}
	}

	function create_tree( ) {
			
		if( count( $this->files ) > 2 ) { /* First 2 entries are . and ..  -skip them */
			natcasesort( $this->files );
			$list = '<ul class="filetree" style="display: none;">';
			// Group folders first
			foreach( $this->files as $file ) {
				if( file_exists( $this->folder . $file ) && $file != '.' && $file != '..' && is_dir( $this->folder . $file )) {
					$list .= '<li class="folder collapsed"><a href="#" rel="' . htmlentities( $this->folder . $file ) . '/">' . htmlentities( $file ) . '</a></li>';
				}
			}
			// Group all files
			foreach( $this->files as $file ) {
				if( file_exists( $this->folder . $file ) && $file != '.' && $file != '..' && !is_dir( $this->folder . $file )) {
					$ext = preg_replace('/^.*\./', '', $file);
					$list .= '<li class="file ext_' . $ext . '"><a href="#" rel="' . htmlentities( $this->folder . $file ) . '">' . htmlentities( $file ) . '</a></li>';
				}
			}
			$list .= '</ul>';	
			return $list;
		}
	}
}

$path = urldecode( $_REQUEST['dir'] );
$tree = new treeview( $path );
echo $tree->create_tree();

Here’s the revised version:

<?php

class TreeView {

    private array $files = [];
    private string $folder;
    private $dir; // Resource or false

    function __construct(string $path) {
        if (file_exists($path)) {
            $this->folder = rtrim($path, '/') . '/';
            $this->dir = opendir($path);
            if ($this->dir !== false) {
                while (($file = readdir($this->dir)) !== false) {
                    $this->files[] = $file;
                }
                closedir($this->dir);
            }
        }
    }

    function createTree(): string {
        if (count($this->files) > 2) {
            natcasesort($this->files);
            $list = '<ul class="filetree" style="display: none;">';

            // Group folders first
            foreach ($this->files as $file) {
                if ($this->isValidFile($file) && is_dir($this->folder . $file)) {
                    $list .= '<li class="folder collapsed"><a href="#" rel="' . htmlentities($this->folder . $file) . '/">' . htmlentities($file) . '</a></li>';
                }
            }

            // Group all files
            foreach ($this->files as $file) {
                if ($this->isValidFile($file) && !is_dir($this->folder . $file)) {
                    $ext = preg_replace('/^.*\./', '', $file);
                    $list .= '<li class="file ext_' . $ext . '"><a href="#" rel="' . htmlentities($this->folder . $file) . '">' . htmlentities($file) . '</a></li>';
                }
            }

            $list .= '</ul>';
            return $list;
        }
        return '';
    }

    private function isValidFile(string $file): bool {
        return file_exists($this->folder . $file) && $file !== '.' && $file !== '..';
    }
}

$path = urldecode($_REQUEST['dir'] ?? ''); // Default to empty string if not set
$tree = new TreeView($path);
echo $tree->createTree();

?>

Changes made:

  1. Type Declarations: Added type declarations for properties, method arguments, and return types.
  2. Property Initialization: Initialized the $files property and declared the $dir property.
  3. String Manipulation: Used rtrim to ensure $folder ends with a single slash.
  4. Error Handling: Added checks to ensure $this->dir is not false before reading from it.
  5. Refactoring: Moved the file validation logic into a private method isValidFile for better readability.
  6. Input Validation: Added a null coalescing operator (??) to provide a default empty string if $_REQUEST['dir'] is not set, preventing potential undefined index notices.

Good luck

1 Like

Thank you very much for the revision and detailed explanation.

I want to ask something
To run a function

Sometimes it needs to be like this

function test() {
// 
}
echo test();

Sometimes it needs to be like this

echo test();
function test() {
// 
}

What does this vary depending on?

Also, in this class, I tried a little how Google Drive works, but I couldn’t succeed.

1 Like

In PHP, the way you call a function largely depends on where and how the function is defined. Let’s clarify the two scenarios you mentioned:

1. Calling a Function Before Its Declaration

echo test();
function test() {
    // implementation
}

In PHP, you can call a function before its declaration due to a feature called function hoisting. This means that PHP internally moves function declarations to the top of their respective scopes before executing the code. This feature is specific to functions and does not apply to variables or classes.

2. Calling a Function After Its Declaration

function test() {
    // implementation
}
echo test();

This is the more traditional and widely-used approach where you declare a function first and then call it later in your script. It’s straightforward and works in all programming languages, not just PHP.

When to Use Each Approach

  • Prefer the Second Approach: It is generally recommended to declare your functions before you call them. This approach is clearer and more maintainable, especially in large codebases or when working in a team.
  • Function Hoisting: Use the first approach (function hoisting) sparingly. It can lead to confusion, especially for developers who might not be familiar with this feature of PHP or are accustomed to other programming languages where this behavior is not present.

Regarding Your TreeView Class and Google Drive Functionality

  • Your TreeView class is designed to generate an HTML representation of the files and directories in a given path. This is a good start for a basic file browsing feature.
  • Google Drive-like Functionality: Implementing functionality similar to Google Drive involves much more than just listing files and directories. Google Drive features include file storage, sharing, real-time collaboration, version control, etc. These features require a backend to handle file storage (like cloud storage solutions), user authentication, database management for storing file metadata, and front-end development for the user interface.
  • Expanding Your Class: If you’re interested in expanding your TreeView class, consider what specific Google Drive features you want to mimic. For a simple file storage and sharing system, you might start with user authentication, file upload/download capabilities, and a database to store file information and user permissions.

Remember, building a system with functionalities similar to Google Drive is a complex and extensive project, requiring knowledge in several areas of web development, including both front-end and back-end technologies.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service