PHP Archives | phpGrid - PHP Datagrid Create PHP grids in minutes, not hours. Tue, 11 Mar 2025 22:26:35 +0000 en-US hourly 1 CodeProjecthttps://wordpress.org/?v=7.0.3 129966043 Understanding Asymmetric Property Visibility in PHP 8.4 https://phpgrid.com/blog/understanding-asymmetric-property-visibility-in-php-8-4/ Mon, 17 Mar 2025 22:26:16 +0000 https://phpgrid.com/?p=10232 PHP 8.4, released in November 2024, introduces Asymmetric Property Visibility, which allows separate visibility levels for reading and writing class properties, enhancing access control while preserving encapsulation. What is Asymmetric Property Visibility? In PHP 8.4, you can now define different visibility levels for reading and writing a property within a class. Previously, PHP allowed properties […]

The post Understanding Asymmetric Property Visibility in PHP 8.4 appeared first on phpGrid - PHP Datagrid.

]]>
PHP 8.4, released in November 2024, introduces Asymmetric Property Visibility, which allows separate visibility levels for reading and writing class properties, enhancing access control while preserving encapsulation.

What is Asymmetric Property Visibility?

In PHP 8.4, you can now define different visibility levels for reading and writing a property within a class.

Previously, PHP allowed properties to be (public), (protected), or (private), but both reading and writing had the same visibility level. With Asymmetric Property Visibility, you can set separate visibility for getting and setting a property.

A Basic Example

class User {
    public string $name { public get; private set; }

    public function __construct(string $name) {
        $this->name = $name; // Allowed: private setter is used inside the class
    }

    public function changeName(string $newName) {
        $this->name = $newName; // Allowed: inside class
    }
}

$user = new User("Alice");
echo $user->name; // ✅ Allowed: public getter
$user->name = "Bob"; // ❌ Error: Cannot modify, setter is private

Key Takeaways

  • (get) visibility is public, allowing read access from anywhere.
  • (set) visibility is private, so only class methods can modify the property.

Example 2: Preventing Direct Modification of Sensitive Properties

class BankAccount {
    public int $balance { public get; private set; }

    public function __construct(int $initialBalance) {
        $this->balance = $initialBalance;
    }
    public function deposit(int $amount) {
        $this->balance += $amount; // ✅ Allowed: inside class
    }
    public function withdraw(int $amount) {
        if ($amount > $this->balance) {
            throw new Exception("Insufficient funds");
        }
        $this->balance -= $amount; // ✅ Allowed: inside class
    }
}

$account = new BankAccount(1000);
echo $account->balance; // ✅ Allowed: public getter
$account->balance = 500; // ❌ Error: Cannot modify, setter is private

Key Takeaways

  • Prevents unauthorized modifications to ($balance) while allowing controlled updates through class methods.
  • Improves security by ensuring logic (e.g., preventing overdrafts) is always enforced.

Caveats & Considerations

  • This feature only applies to typed properties ((int), (string), (array), etc.). Typed properties are supported since PHP 7.4
  • You must specify a visibility level for both (get) and (set) (e.g., ({ public get; private set; })).
  • Asymmetric visibility cannot be applied to untyped properties.

How Was Asymmetric Property Visibility Achieved Before PHP 8.4?

Before Asymmetric Property Visibility, PHP only allowed single visibility for properties ((public), (protected), or (private)). This meant that if a property was readable, it was also writable unless additional methods were used to restrict modifications.

To achieve similar behavior, developers had to use getter and setter methods manually using Getter & Setter Methods (Manual Encapsulation)

For example:

class User {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    // Public getter method
    public function getName(): string {
        return $this->name;
    }

    // Private setter method (prevents external modification)
    private function setName(string $name): void {
        $this->name = $name;
    }

    public function changeName(string $newName): void {
        $this->setName($newName); // Allowed inside class
    }
}

$user = new User("Alice");

echo $user->getName(); // ✅ Allowed: public getter\
$user->setName("Bob"); // ❌ Error: Cannot access private method\
$user->name = "Bob"; // ❌ Error: Cannot access private property

Problems with the Traditional Approach

  1. More Boilerplate Code
  • Requires explicit getter and setter methods for each property.
  • Increases code duplication when dealing with many properties.

2. Less Readable & Natural Code

  • Instead of ($user->name), you need to call ($user->getName()).
  • Assigning a value (($user->name = “Bob”;)) is replaced by a method (($user->changeName(“Bob”);)).

Why Asymmetric Property Visibility Matters

Asymmetric Property Visibility in PHP 8.4 enhances encapsulation by allowing developers to set different visibility levels for reading and writing a property. This means a property can be publicly readable but privately writable, preventing unintended modifications while still making data accessible. 

Previously, achieving this required workarounds like getter and setter methods, but now it can be done more cleanly and intuitively. This feature improves code maintainability, security, and clarity, making it easier to enforce strict control over property access without extra boilerplate.

Final Thoughts

Before PHP 8.4, getter and setter methods were the only way to enforce asymmetric visibility. While effective, it resulted in verbose and less readable code. With Asymmetric Property Visibility, PHP now provides native support for defining different access levels for reading and writing properties, making property management much cleaner and more intuitive.

The post Understanding Asymmetric Property Visibility in PHP 8.4 appeared first on phpGrid - PHP Datagrid.

]]>
10232
Debugging PHP with VSCode and XDebug: A Step-by-Step Guide https://phpgrid.com/blog/debugging-php-with-vscode-and-xdebug-a-step-by-step-guide/ Tue, 11 Mar 2025 04:46:39 +0000 https://phpgrid.com/?p=10227 Debugging is an essential part of PHP development, and using Visual Studio Code with XDebug can greatly enhance your workflow. This guide will walk you through setting up XDebug, enabling breakpoints, stepping through code, using stack traces, and troubleshooting common issues. 1. Installing XDebug Before you can debug PHP with VSCode, you need to ensure […]

The post Debugging PHP with VSCode and XDebug: A Step-by-Step Guide appeared first on phpGrid - PHP Datagrid.

]]>
Debugging is an essential part of PHP development, and using Visual Studio Code with XDebug can greatly enhance your workflow. This guide will walk you through setting up XDebug, enabling breakpoints, stepping through code, using stack traces, and troubleshooting common issues.

1. Installing XDebug

Before you can debug PHP with VSCode, you need to ensure that XDebug is installed on your system.

Check if XDebug is Installed

From a phpinfo page, and check wether XDebug section and it is enabled.

XDebug in phpinfo

Install XDebug If It Is Missing

If XDebug is missing, you can install it using pecl:

pecl install xdebug

After installation, add this line to your php.ini file:

zend_extension=xdebug

Remembere to restart your web server or PHP service:

sudo systemctl restart apache2 # For Apache
sudo systemctl restart php-fpm # For PHP-FPM

Now we need to configure XDebug to connect to VSCode

2. Configuring XDebug for VSCode

Edit your php.ini file and add the following configuration:

[xdebug]
xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_host=127.0.0.1
xdebug.client_port=9003
xdebug.log=/var/log/xdebug.log

Important:

Ensure your PHP service is restarted for any changes made in php.ini to take effect.

3. Setting Up VSCode for XDebug

1. Install the PHP Debug Extension

PHP Debug Extension for VSCode

2. Configure VSCode Debugger

  • Open your project in VSCode.
  • Go to the Run and Debug panel (Ctrl+Shift+D).
  • Click on create a launch.json file. It should create default configuration as the following with port 9003. It is absolutely critial to have the same port as what is in xdebug.client_port in php.ini in previous step.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
   "version": "0.2.0",
    "configurations": [        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9003
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9003
        }
    ]
}

3. Start the Debugger

  • Click the green Start Debugging button or press F5.
  • Ensure XDebug is running and listening on port 9003. It actually can be any port number as 9003 is default.

The debugger bar should now appear right below tabs in VSCode.

VSCode Debugger Bar

4. Debugging Features

Setting Breakpoints

  • Open any PHP file.
  • Click in the left margin next to a line number or press F9 to set a breakpoint.
  • Run the debugger (F5) and execute the PHP script in your browser.
  • The script execution will pause at the breakpoint.

Stepping Through Code

While debugging, you can control execution using:

  • Step Over (F10) – Move to the next line of code.
  • Step Into (F11) – Enter into function calls.
  • Step Out (Shift+F11) – Exit the current function.
  • Continue (F5) – Resume execution until the next breakpoint.

Using Stack Trace

  • The Call Stack panel in VSCode shows the sequence of function calls leading up to the breakpoint.
  • Helps trace errors in deeply nested functions.
  • Click on any function in the stack to inspect its execution.

PHP XDebug breakpoint

5. Troubleshooting Common Issues

Issue 1: Debugger Not Stopping at Breakpoints

  • Ensure XDebug is installed and configured correctly in phpinfo (See step 1)
  • Make sure the matching port (e.g. 9003) is set in both php.ini and launch.json.
  • Always restart Apache or PHP-FPM after making changes.

Issue 2: XDebug Not Connecting to VSCode

  • Verify the logs in =/var/log/xdebug.log for connection issues.
  • Ensure VSCode is listening for XDebug (F5 in debug mode).
  • Disable other applications using port 9003 (like another debugger).

Issue 3: Path Mapping Problems

  • Ensure pathMappings in launch.json correctly maps the server path to the local workspace
  • Add $_SERVER[‘DOCUMENT_ROOT’] in your script to verify paths.

Conclusion

VSCode and XDebug together make debugging PHP a seamless experience. By following this guide, you should be able to install and configure XDebug properly, and set breakpoints and step through code, and also troubleshoot common debugging issues.

Finally, if manually tinkering isn’t your thing, you can opt for a hassle-free solution like MAMP or XAMMP.

Happy debugging! 🚀

Richard

The post Debugging PHP with VSCode and XDebug: A Step-by-Step Guide appeared first on phpGrid - PHP Datagrid.

]]>
10227