Warning! The RK-CMS distribution is distributed exclusively through rk-cms.ru. Downloading copies from third-party resources may result in data loss or installation of malware.

Menu
    300 140

    Many developers naively cast data to types. This results in an unknown result and a lack of control.

    For example, (array):

    $ab = (array)$data;

    If $data is a string or an object, we get something uncontrollable.
    We believe that there should be a correspondence, not an equality. And instead of

    $ab = (array)$data;

    it's better to write in a controlled manner:

    if (!is_array($data)) { $data = array(); }

    When you write (array)$data, you're telling PHP, "Make this variable into an array, however you want." But PHP doesn't know what you want. As a result:

    If $data was the string "hello," you'd get array("hello")—an array with one element.

    If $data was the number 123, you'll get array(123).

    If $data was an object, you'll get an array of its properties, but with special rules (private properties get strange names, nested objects aren't converted recursively, etc.).

    If $data was null, you'll get an empty array.

    If $data was already an array, it will remain as is.

    It seems convenient—one line and you're done. But the problem is that you don't control the result. You think, "Now I have an array, everything is fine." But in reality, what's inside might be completely different from what you expected.

    This leads to hidden errors: somewhere further in the code, you access array elements that don't exist, or their structure is incorrect.

    Type casting using (array), (int), and similar constructs is a quick but dangerous method.

    It hides the variable's actual contents and creates the illusion of control. It's much safer to write code that explicitly checks the type and handles each case. Yes, it's a little more code, but your code will be clear, predictable, and free of surprises.

    We use cookies to improve the functioning of the site and its interaction with users. By continuing to use the site, you consent to the use of cookies (find out more).

    You can always disable cookies in your browser settings.