What are accessors and mutators?

Understand accessors and mutators with real-world examples. Learn how to format and modify model data automatically.

In object‑oriented programming, accessors (also known as getters) and mutators (also known as setters) are public methods whose only job is to retrieve or update the value of a class member variable.

Why not use public variables directly?

While it’s technically easier to declare member variables as public, using getters and setters brings major advantages in terms of:

Encapsulation: Data and the methods that operate on it are bundled, and implementation details remain hidden from external code. This separation makes the internal workings of a class changeable without breaking external usage.

Data validation: Setters allow you to enforce rules before updating a value—for instance, preventing setting a value outside an acceptable range.

Naming Conventions

Getter: getVariableName() — returns the value of a private variable.

Setter: setVariableName(newValue) — modifies the value, optionally with validation logic.

Examples

This example shows how getters and setters can be used in Java.

public class Account {
    private int balance;

    public int getBalance() {
        return balance;
    }

    public void setBalance(int newBalance) {
        if (newBalance >= 0) {
            balance = newBalance;
        }
    }
}

Similarly, this example shows usage og getters and setters using Python.

class Person:
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, new_name):
        if new_name:
            self.__name = new_name

In this Python example, the @property decorator defines an accessor, while the @name.setter decorator defines a mutator.

Same accessors and mutators can be defined in other languages as well like PHP, Ruby, C#, etc.

Why Use Accessors/Mutators?

Better Encapsulation: Clients of your class interact through methods, not direct access to data.

Safe Updates: Setters can catch invalid data before it gets saved (e.g., negative numbers, abusive inputs).

Maintain Interface Stability: You can refactor or change internal data structures later without affecting external callers.

Customization & Control: Getters can return derived values, or trigger lazy computation; Setters can log events, enforce thread safety, etc.

Community Insight

In everyday developer conversations—such as on forums or Stack Overflow—it’s common to see that “accessor” = getter and “mutator” = setter. Many fall back to the more familiar terms “getters and setters,” and treat them interchangeably.

Conclusion

Accessors and mutators are foundational to good object‑oriented design. They help you build robust, maintainable, and secure classes. Instead of exposing variables directly, these methods provide controlled interaction with internal data, enforcing rules, maintaining invariants, and preserving encapsulation.

Python Geocoding: Convert Addresses to Coordinates Easily

Learn how to convert physical addresses into geographic coordinates using Python libraries like Geopy. Step-by-step geocoding tutorial for beginners.

Most of the time, datasets are incomplete and often require pre-processing to make them usable. Imagine, We have some datasets with only an address column without latitude and longitude columns, and we want to represent this data geographically. To do that, we need to add geographic information to these data. These cannot be possible manually. We have to create a script to convert all those addresses to geographic information – Latitude and Longitude – to map their locations, which is known as Geocoding. We can do this geocoding using python geopy library.

Geocoding is the computational process of transforming a physical address description to a location on the Earth’s surface (spatial representation in numerical coordinates)

Wikipedia

In this article, I will show you how to perform geocoding in Python with the help of Geopy library. Geopy has different Geocoding services that you can choose from, including Google Maps, ArcGIS, AzureMaps, Bing, etc. Some of them require API keys, while others can be accessible freely.

Install Geopy

To perform geocoding, we need to install the following Geopy library using pip,

pip install geopy

Geocoding Single Address

In this example, we use Nominatim Geocoding service, which is built on top of OpenStreetMap data.

Let us Geocode a single address, the Taj Mahal in Agra, India.

locator = Nominatim(user_agent="myGeocoder")
location = locator.geocode("Taj Mahal, Agra, India")

First line of the above code will create locator that holds the Geocoding service, Nominatim. In second line, we call geocode method of the locator service and pass any address to it, in this example, the Taj Mahal address.

print("Latitude = {}, Longitude = {}".format(location.latitude, location.longitude))

Above line will print out the coordinates of the location we have created.

Latitude = 48.85614465, Longitude = 2.29782039332223

That’s it.

So, the complete code will look like this,

import geopy
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter

locator = Nominatim(user_agent="myGeocoder")
geocode = RateLimiter(locator.geocode, min_delay_seconds=1)

address = "Taj Mahal, Agra, India"
location = locator.geocode(address)

print("Latitude = {}, Longitude = {}".format(location.latitude, location.longitude))

Now, try some different addresses of your own.

Detecting Bugs in PHP Code with PHPStan: A Static Analysis Tool

Learn how to detect bugs early in your PHP codebase using PHPStan, a powerful static analyzer. Improve code quality with practical tips and examples.

Writing clean, bug-free code is a goal for every developer — but manual testing and reviews aren’t always enough. That’s where static analysis tools like PHPStan come in. PHPStan helps you catch bugs in your PHP code without executing it. By analyzing your source files, it detects potential issues before they ever become runtime errors.

In this article, we’ll explore what PHPStan is, how it works, and how you can integrate it into your PHP projects to improve code quality.

What is PHPStan?

PHPStan is a static analysis tool specifically designed for PHP. It scans your codebase and finds problems such as:

  • Type mismatches
  • Undefined variables or methods
  • Dead or unreachable code
  • Incorrect method calls

Unlike traditional debuggers, PHPStan doesn’t execute your code — it reads and analyzes your PHP files directly, looking for structural or logical inconsistencies based on static rules.

Why Use PHPStan?

Here are a few reasons to integrate PHPStan into your development workflow:

  • Early bug detection: Spot bugs before running the code.
  • Improved code quality: Enforce strict typing and coding standards.
  • Reduced runtime errors: Catch potential issues during development.
  • Better refactoring: Safely restructure code with confidence.

PHPStan becomes especially powerful when used alongside modern PHP features like type hints, union types, and generics.

Getting Started with PHPStan

Installing PHPStan is very easy. You can install it in your project through composer:

$ composer require --dev phpstan/phpstan

This installs PHPStan as a development dependency.

Running PHPStan

We can now run PHPStan from the base directory of our project. To analyze your code, use the following command:

$ vendor/bin/phpstan analyze src

Replace src with the directory containing your PHP files.

A breakdown of this command:

  • vendor/bin/phpstan is the executable
  • analyze tells PHPStan to analyze all files in the given directories
  • src is the directory we want to analyse

Try running this in your own project and see what kind of potential errors are living in your codebase.

By default, PHPStan analyzes the code with a conservative level of strictness. However, you can make it more strict using levels from 0 (lenient) to 8 (strictest):

vendor/bin/phpstan analyse src --level=5

Configuration with phpstan.neon

For more control, you can create a phpstan.neon configuration file in your project root:

parameters:
    level: 5
    paths:
        - src
        - app
    ignoreErrors:
        - '#Call to an undefined method.*#'

This allows you to customize which folders to analyze, define rules to ignore, and adjust the strictness level.

Common Issues Caught by PHPStan

PHPStan can detect a wide range of issues:

  • Calling methods or accessing properties that don’t exist.
  • Passing the wrong type of arguments to a function or method.
  • Returning values of the wrong type.
  • Forgetting to return a value in non-void functions.
  • Using undefined variables.

These issues often lead to hard-to-find bugs in production. Catching them early saves time and effort.

Integrating PHPStan into CI

To make PHPStan even more effective, integrate it into your CI/CD pipeline. This ensures code is analyzed automatically on every push or pull request, helping maintain a high standard across your team.

For most of my personal projects, I use TravisCI. Since we’ve included PHPStan as a dev-dependency in our composer.json file we just have to add the PHPStan executable to the scripts that the CI-software needs to run.

For TravisCI, this means just changing the default script in a .travis.yml like this:

language: php
php:
  - '8.0'
install: composer install

# Simply add these lines
script:
    - vendor/bin/phpunit
    - vendor/bin/phpstan analyse src tests --level=5

The default script that TravisCI runs for PHP projects is phpunit. Now we’ve added PHPStan to it. If PHPStan finds any errors within your project, the build will fail.

Similarly, in GitHub Actions:

- name: Run PHPStan
  run: vendor/bin/phpstan analyse --level=5

Conclusion

PHPStan is a must-have tool for modern PHP development. It helps you catch bugs early, write cleaner code, and reduce technical debt over time. Whether you’re maintaining a legacy project or starting a new one, integrating PHPStan into your workflow is a smart move.

Advanced Error Handling in PHP (Part 2)

Explore advanced techniques for error handling in PHP including exceptions, custom error handlers, and best practices in Part 2 of this series.

Now that we know, how to log errors in any system developed in PHP, we can move to our next section for keeping track of these logged errors. If you haven’t read how to log errors, read part 1 of error handling in PHP.

To keep track of these logged errors, we need to create a script to read those log files in a systematic way. Refer to the below code to read log files,

public function errorLogs($filePath = 'error.log') {

        $fileContent = file($filePath);

        $errorsArray = array();
        if(sizeof($fileContent) == 0) {
            return false;
        }

        foreach($fileContent as $row) {
            $errors = explode(":  ", $row);

            if(empty($errors[1])) continue;
            $errorsArray[] = $errors;
        }

        return array_reverse($errorsArray, true);
}

Explanation:

$fileContent = file($filePath);

This line of code will read the file line by line from the provided file path.

if(sizeof($fileContent) == 0) {
    return false;
}

After reading the file, if the size of the file content is 0 then, the function will return false. So, the purpose of this function is to stop the execution of the function if the provided file is empty and returns false.

foreach($fileContent as $row) {
      $errors = explode(":  ", $row);

      if(empty($errors[1])) continue;
      $errorsArray[] = $errors;
}

This part of the function will loop through the log contents row by row. For each row, it will explode the line with ‘:’ to separate the date and actual error details.

If the error details are empty for any row, it will skip that row. Otherwise, it will collect the errors in another array.

return array_reverse($errorsArray, true);

The last line of the function will reverse the error data and returned the reversed result. So, that we can see the latest errors first.

This way we can create a simple function to display the list of errors in a tabular format from the error log files we generated for each of the modules in the application system.

Beginner’s Guide to Error Handling in PHP – Part 1

Learn the basics of error handling in PHP. Understand types of errors, how to display them, and the use of error_reporting() and ini_set() functions.

Error handling is an important part of any developer as it provides vital flaws about the program developed by the developer. So, it becomes very crucial to learn the techniques to manage it.

As a developer, we have been told that you should not show errors on the production server because of the security risk due to the path displayed by the PHP errors displayed on the screen. So, we add the following code for the production server,

ini_set('error_reporting', 0);
error_reporting(0);

ini_set('display_errors', FALSE);

But, without error logs, developers cannot able to know actual problems or flaws in the system. So, rather than hiding errors, developers should store them in the log files. We can achieve this using the following code,

ini_set('error_reporting', E_ALL);
error_reporting(E_ALL);
ini_set('log_errors', TRUE);
ini_set('html_errors', FALSE);
ini_set('error_log', LOG_PATH.'error.log');
ini_set('display_errors', FALSE);

This way, we can manage error logs and hide errors on the production server. We can manage separate log files for the different modules of the project.