Category: Coding & Scripting

PHP: when should I use ‘self’ and when should I use ‘$this’?

php logo on purple background

In PHP, the keyword $this is used to refer to the current instance of the class, while the keyword self is used to refer to the class itself.

You should use $this when referring to instance-level properties or methods within the same class, such as when accessing a property of the current object or calling a method of the current object.

For example:

class MyClass {
    private $name;

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

    public function sayHello() {
        echo "Hello, my name is " . $this->name;
    }
}

$obj = new MyClass("John");
$obj->sayHello(); // output: "Hello, my name is John"

On the other hand, you should use self when referring to static properties or methods within the same class, such as when accessing a static property or calling a static method of the class.

For example:

class MyClass {
    private static $count = 0;

    public function __construct() {
        self::$count++;
    }

    public static function getCount() {
        return self::$count;
    }
}

$obj1 = new MyClass();
$obj2 = new MyClass();
echo MyClass::getCount(); // output: 2

In summary, $this is used for instance-level properties and methods, while self is used for static properties and methods.

 

PHP: How to check if a string contains a specific word?

php logo on purple background

You can check if a string contains a specific word in PHP by using the strpos() function, the preg_match() function or the str_contains() function.

Using strpos()

The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found, it returns false. You can use this function to check if a string contains a specific word as follows:

$string = "This is a sample string.";
$word = "sample";

if (strpos($string, $word) !== false) {
    echo "The string contains the word.";
} else {
    echo "The string does not contain the word.";
}

In this example, we first define a string $string and a word $word. Then, we use the strpos() function to check if the $string contains the $word. If the $word is found in the $string, the function will return a position value that is not false, and the output will be “The string contains the word.” Otherwise, the function will return false, and the output will be “The string does not contain the word.”

Using preg_match()

The preg_match() function searches a string for a pattern and returns true if the pattern is found, and false otherwise. You can use this function to check if a string contains a specific word as follows:

$string = "This is a sample string.";
$word = "/sample/";

if (preg_match($word, $string)) {
    echo "The string contains the word.";
} else {
    echo "The string does not contain the word.";
}

Using str_contains()

The str_contains() method is available in PHP 8 and higher versions. You can use this method to check if a string contains a specific word as follows:

$string = "This is a sample string.";
$word = "sample";

if (str_contains($string, $word)) {
    echo "The string contains the word.";
} else {
    echo "The string does not contain the word.";
}

Performance Comparison

When comparing the performance of those three methods, we get the following result:

strpos()1.37e-7 seconds = 0.137 micro seconds
preg_match()1.54e-7 seconds = 0.154 micro seconds
str_contains()1.28e-7 seconds = 0.128 micro seconds

So the new method str_contains() (for PHP 8.0 or higher) is the fastest one.

For the results, the mean execution time in a loop with 1,000,000 cycles was calculated for each method.

 

Dart: What is the difference between the “const” and “final” keywords?

Dart programming language logo

In Dart, both const and final are used to declare variables that can’t be reassigned after they’re initialized. However, there are some differences between them:

  1. const is used to declare a compile-time constant. The value of a const variable must be known at compile time. When you create an object using const, Dart ensures that there is only one instance of that object. const can be used to create constant values of built-in types, as well as classes and collections that are also const.
  2. final is used to declare a variable that can only be set once. It doesn’t have to be initialized at compile-time, but once it’s initialized, it can’t be changed. final can be used to create non-constant values of built-in types, as well as classes and collections that are not const.

In general, use const when you have a value that will never change and you want to ensure that only one instance of it exists, and use final when you have a value that won’t change but can’t be known at compile time.

Example Usage

class MyClass {
  final int a;
  static const int b = 10;

  MyClass(this.a);

  void printValues() {
    print('a: $a');
    print('b: $b');
  }
}

void main() {
  final obj = MyClass(5);
  obj.printValues();
}

In this example, we have a class MyClass with two member variables a and b. a is declared as final, which means that it can only be assigned once, either in the constructor or when it’s declared. b is declared as static const, which means that it’s a compile-time constant and there is only one instance of it across all instances of the class.

In the constructor of MyClass, we assign the value of a. When we create an instance of MyClass in main(), we pass the value 5 to the constructor, which assigns it to a.

Then, we call the method printValues(), which prints the values of a and b. Since b is declared as static const, we can access it using the class name (MyClass.b) instead of an instance of the class.

Overall, final and const are useful in classes to create immutable values that can’t be changed once they’re initialized. final is used for values that can be initialized at runtime, while const is used for values that can be initialized at compile-time.

Flutter: How to Create a Color from a Hexadecimal Color String

colored pencils

In Flutter, you can create a color from a hexadecimal color string value using the Color class. The Color class takes a 32-bit integer value as an argument, where the first 8 bits represent the alpha channel (transparency) and the remaining 24 bits represent the red, green, and blue channels.

To create a color object from a hexadecimal color string value, you need to pass the value to the Color() constructor. For example, to create the color red, you can use the following code:

Color color = Color(0xFFFF0000);

To create a color from a hexadecimal string value, you need to convert the string to a 32-bit integer value first. Here’s an example of how to do it:

String hexColor = "#FF0000"; // red color
Color color = Color(int.parse(hexColor.substring(1, 7), radix: 16) + 0xFF000000);

In the above code, the substring(1, 7) method is used to remove the “#” character from the hexadecimal color string. The int.parse() method converts the remaining string into a 32-bit integer value using the radix argument, which specifies that the string is in base 16 (hexadecimal). The + 0xFF000000 part adds the alpha channel value of 255 (fully opaque) to the color value.

Colors with Transparency

You can also create colors with transparency using an eight-digit hexadecimal color string value. The first two digits represent the alpha channel, which controls the opacity of the color. For example, to create a semi-transparent red color, you can use the following code:

Color semiTransparentColor = Color(0x80FF0000);

Or for a given string value:

String hexColor = "#FF0000"; // red color
Color semiTransparentColor = Color(int.parse(hexColor.substring(1, 7), radix: 16) + 0x80000000);

Here, 0x80FF0000 is the hexadecimal color value for red with 50% transparency. The first two digits “80” represent the alpha channel, and the remaining six digits represent the color components.

Usage in Widgets

You can now use the color object to set the color of any widget in your Flutter application:

Container(
  color: color,
  child: ...
)

You can also use the color object as a parameter in some widgets, such as the IconButton widget. Here’s an example:

IconButton(
  icon: Icon(Icons.add),
  color: color, 
  onPressed: () {}, 
)

Foto von Ramakant Sharda auf Unsplash

Pecl: fixing “fatal error: ‘pcre2.h’ file not found”

yellow and black stripes

When using pecl to install a PHP extension, I always got a “fatal error: ‘pcre2.h’ file not found” after PHP has been updated. The update was done using brew upgrade php. In my case, this happens when I try to install pcov using:

pecl install pcov

The output was:

In file included from /private/tmp/pear/temp/pcov/pcov.c:26:
/opt/homebrew/Cellar/php/8.2.2/include/php/ext/pcre/php_pcre.h:23:10: fatal error: 'pcre2.h' file not found
#include "pcre2.h"
         ^~~~~~~~~

To fix the issue, make sure you have pcre2 installed:

brew install pcre2

After this, create a symlink to the pcre2.h file:

ln -s /opt/homebrew/Cellar/pcre2/10.42/include/pcre2.h /opt/homebrew/Cellar/php/8.2.2/include/php/ext/pcre/pcre2.h

Make sure, to adjust the versions of pcre2 and php (or any other package where you got the error). In my case it’s PHP version 8.2.2 (see the error message) and pcre2 version 10.42.

After the symlink was created, the installation of pcov finished without errors:

Build process completed successfully
Installing '/opt/homebrew/Cellar/php/8.2.2/pecl/20220829/pcov.so'
install ok: channel://pecl.php.net/pcov-1.0.11
Extension pcov enabled in php.ini

Foto von Scott Rodgerson auf Unsplash.

jQuery methods in plain JavaScript

cup of coffee

Life is already very complex, so let’s simplify your projects by removing all the jQuery code. Plain JavaScript provides the same functionalities and it does not require any additional frameworks. And it’s supported by most of the modern browsers out of the box. This is a list of replacements for your daily used jQuery methods.

$() or jQuery()

Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.

// jQuery implementation
var element = $(selector);
// Plain JavaScript
var element = document.querySelector(selector); // Single element
var elements = document.querySelectorAll(selector); // Multiple elements

.addClass()

Adds the specified class(es) to each element in the set of matched elements.

// jQuery implementation
element.addClass('text-bold');
// Plain JavaScript
element.classList.add('text-bold');

.attr()

Adds the specified class(es) to each element in the set of matched elements.

// jQuery implementation
element.attr(attribute, value);
// Plain JavaScript
element.setAttribute(attribute, value);

.css()

Set one or more CSS properties for the set of matched elements.

// jQuery implementation
element.css(property, value);
// Plain JavaScript
element.style[property] = value;

.each()

Iterate over a jQuery object, executing a function for each matched element.

// jQuery implementation
$.each(settings, function (index, element) {
    // ...
});
// Plain JavaScript
settings.forEach((element, index) => {
    // ...
});

.empty()

Remove all child nodes of the set of matched elements from the DOM.

// jQuery implementation
container.empty();
// Plain JavaScript
container.replaceChildren();

See https://stackoverflow.com/a/65413839/768352

.extend()

Merge the contents of two or more objects together into the first object.

// jQuery implementation
const settings = $.extend(defaults, options)
// Plain JavaScript
const settings = {...defaults, ...options}

.hasClass()

Determine whether any of the matched elements are assigned the given class.

// jQuery implementation
if (element.hasClass('text-bold')) {
  // ...
}
// Plain JavaScript
if (element.classList.contains('text-bold')) {
  // ...
}

.hide()

Hide the matched elements.

// jQuery implementation
element.hide();
// Plain JavaScript
element.style.display = 'none';

.html()

Set the HTML contents of each element in the set of matched elements.

// jQuery implementation
element.html('<div>my html</div>');
// Plain JavaScript
element.style.innerHTML = '<div>my html</div>';

.map()

Translate all items in an array or object to new array of items.

// jQuery implementation
$.map(array, function (value, index) {});
// Plain JavaScript
array.map((value, index) => {});

.now()

Return a number representing the current time.

// jQuery implementation
$.now();
// Plain JavaScript
Date.now();

.removeClass()

Remove a single class or multiple classes from each element in the set of matched elements.

// jQuery implementation
element.removeClass('text-bold');
// Plain JavaScript
element.classList.remove('text-bold');

.show()

Display the matched elements.

// jQuery implementation
element.show();
// Plain JavaScript
element.style.display = 'block';

.text()

Set the content of each element in the set of matched elements to the specified text.

// jQuery implementation
element.text('my text');
// Plain JavaScript
element.textContent = 'my text';

.toggle()

Display or hide the matched elements.

// jQuery implementation
element.toggle();
// Plain JavaScript
element.style.display = element.style.display === 'none' ? 'block' : 'none';

.toggleClass()

Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.

// jQuery implementation
element.toggleClass('text-bold');
// Plain JavaScript
element.classList.toggle('text-bold');

.trigger()

Execute all handlers and behaviors attached to the matched elements for the given event type.

// jQuery implementation
$(document).trigger("myEvent");
$(".container").trigger("myEvent");

// Plain JavaScript
document.dispatchEvent(new Event("myEvent"));
document.querySelector(".container").dispatchEvent(new Event("myEvent"));

.val()

Get the current value of the first element in the set of matched elements.

// jQuery implementation
var val = element.val();
// Plain JavaScript
var val = element.value;

Photo by Jakub Dziubak on Unsplash

PHP: Function utf8_decode() and utf8_encode() have been deprecated

php logo on purple background

The utf8_encode() and utf8_decode() functions in PHP are used for encoding and decoding strings between ISO-8859-1 (Latin-1) encoding and UTF-8 encoding.

While PHP’s standard library does include utf8_encode and utf8_decode functions, they are limited to converting between ISO-8859-1 (Latin-1) and UTF-8 encodings. It is important to note that these functions cannot be relied upon to detect and convert other character encodings, such as Windows-1252, UTF-16, and UTF-32, to UTF-8. Attempting to use these functions with arbitrary text can introduce bugs that may not produce any warnings or errors, but can result in unexpected and undesired outcomes.

Examples of common bugs that can occur include:

  • The Euro sign (character sequence \xE2\x82\xAC), when passed to utf8_encode function as utf8_encode("€") results in a a garbled (also called as “Mojibake”) text output of â¬.
  • The German Eszett character (ßcharacter sequence \xDF), when passed through utf8_encode("ß") results in Ã.

The utf8_encode and utf8_decode functions have been deprecated in PHP 8.2 due to their misleading function names, lack of error messages and warnings, and their inability to support character encodings other than ISO-8859-1.

As a result, using these functions in PHP 8.2 will emit a deprecation notice. It is recommended to use alternative functions or libraries that provide better support for handling different character encodings. These functions will be removed entirely in PHP 9.0, so it is important to migrate to alternative solutions as soon as possible to avoid compatibility issues in future versions of PHP.

utf8_encode('foo');

// Function utf8_encode() is deprecated in ... on line ...
uft8_decode('foo');

// Function uft8_decode() is deprecated in ... on line ...

Replacement for the deprecated functions

Instead, the PHP documentation recommends using the multibyte string functions that are part of the mbstring extension for handling multibyte encodings, including UTF-8. For example, the mb_convert_encoding() function can be used to convert strings between different character encodings, including to and from UTF-8.

Replacement for utf8_encode()

Here is an example of how to use mb_convert_encoding() to encode a string to UTF-8:

$string = "Some string with non-ASCII characters: é, ö, ü";
$utf8_string = mb_convert_encoding($string, 'UTF-8');

Replacement for utf8_decode()

And here is an example of how to use mb_convert_encoding() to decode an UTF-8 string:

$utf8_string = "Some UTF-8 encoded string: é, ö, ü";
$string = mb_convert_encoding($utf8_string, 'ISO-8859-1', 'UTF-8');

Source: https://php.watch/versions/8.2/utf8_encode-utf8_decode-deprecated

Flutter: How to remove the debug banner during development

Flutter logo

By default, Flutter shows a debug banner on the top right corner of an app, that indicates that the app was build in debug mode.

screenshot of a Flutter app having a debug banner

This banner…

… is intended to deter people from complaining that your app is slow when it’s in debug mode. In debug mode, Flutter enables a large number of expensive diagnostics to aid in development, and so performance in debug mode is not representative of what will happen in release mode.

https://api.flutter.dev/flutter/material/MaterialApp/debugShowCheckedModeBanner.html

But sometimes you want to remove this banner because it overlaps UI elements or other view elements. To do so, you can simply remove the debug banner by setting the debugShowCheckedModeBanner property of the MaterialApp widget to false. For example:

MaterialApp(
  debugShowCheckedModeBanner: false,
  // ...
)

This will remove the banner at the top right corner that indicates the app is in debug mode.

This banner is only visible in debug mode. When you compile your app in release mode, this banner is not visible at all.