skip to Main Content

I know that an array and an object are composites, because more than one value can be stored in them, while scalars are "primitive" data, i.e. a single value.

But are compound types really objects?

For example, as in Java, almost everything is an object, an Array, an instantiation of a class, a Map etc., but in PHP, does something similar happen? Array, ArrayObject, Map, etc. Do they inherit from Object?

Or are they just "special" objects?

Where can I find more information about this?

Thank you 🙂

2

Answers


  1. To answer this question:

    But are compound types really objects?

    Answer: Objects are one of the compound data types in PHP, but not all compound data types are objects. Each compound data type serves a specific purpose and is used to handle different kinds of data structures in PHP.

    More details for beginners:
    Scalar data types represent individual values, meaning they can only hold a single value at a time. PHP has four scalar data types:

    $integerVar = 25;
    $floatVar = 6.12;
    $stringVar = "Do you know, PHP can go Native ?";
    $booleanVar = false;
    

    Compound data types can hold multiple values or a collection of values. PHP has two primary compound data types:

    // Array
    $colors = array("blue", "red", "green");
    
    // Object (casting an array)
    $colors = (object)array("blue", "red", "green");
    
    // Object (using a simple stdClass object)
    $person = new stdClass();
    $person->name = "Adam";
    $person->age = 90;
    
    // Object (e.g., a database connection)
    $dbConnection = new mysqli("localhost", "login", "password", "database");
    echo $dbConnection->server_info, "n";
    
    Login or Signup to reply.
  2. But are compound types really objects?

    Given the two compound types array and object (Cf. the two structures JSON is built on), then in PHP this is a clear no: array is array (array or associative array/hashmap) and only objects are really objects.

    String is a scalar in the PHP nomenclature, not an array. There is no char type.

    […] but in PHP, does something similar happen? […] Do they inherit from Object?

    For Array() (nowadays []) nothing inherits from object.

    You can however create objects from classes that implement ArrayAccess, Countable and Traversable to create something array-like which then is an object.

    $object = new ArrayObject(['A']);
    

    Still though, there is no single superclass, PHP has is_object() test, the instanceof operator, and type declarations support for object.

    There are also some interface+class hierarchies in the Standard PHP Library (SPL) and PHP core:

    Where can I find more information about this?

    In the PHP manual in the language reference and in the Standard PHP Library (SPL).


    References:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search