What is the PHP equivalent of the Java object class

In java, we have an object type that can be used to cast to a specific class type. How do we do this in PHP?

Regards, Mithun

+3
source share
5 answers

Common objects in PHP are instances stdClass. However, this is not a base class, that is, classes are not inherited from it unless you specify extends stdClassa class in the declaration.

When specifying anything in (object)in PHP it turns out stdClass. For instance:

$a = array('foo' => 'bar');
$o = (object) $a;
var_dump($o instanceof stdClass); // bool(true)
var_dump($o->foo); // string(3) "bar"

There is no concept of raising and lowering in PHP. You can enter a hint for superclasses or interfaces, but more on that. An object is always recognized as an instance of any class that you create it, for example, with new.

+4

php Java, , PHP- . Java Object, php , , . Java- , toString(), hashCode(), getClass() , php.

Java, , php. php . , $logger- > log ($ obj); __toString(), .

, php, .

:

/**
 * Base class for all custom objects
 * well, not really all, but
 * many of them, especially
 * the String and Array objects
 *
 * @author Dmitri Snytkine
 *
 */
class BaseObject
{

    /**
     * Get unique hash code for the object
     * This code uniquely identifies an object,
     * even if 2 objects are of the same class
     * and have exactly the same properties, they still
     * are uniquely identified by php
     *
     * @return string
     */
    public function hashCode()
    {
        return spl_object_hash($this);
    }

    /**
     * Getter of the class name
     * @return string the class name of this object
     */
    public function getClass()
    {
        return get_class($this);
    }

    /**
     * Outputs the name and uniqe code of this object
     * @return string
     */
    public function __toString()
    {
        return 'object of type: '.$this->getClass().' hashCode: '.$this->hashCode();
    }

}
+3

stdClass ( ftm).

, typecast stdClass , .

$obj = (object) array( 'foo' => 'bar' );

$observer = (Observer) new Subject;

:

, . , stdClass. NULL, . , , . - scalar .

, , , :

+2

Ciaran ,

, , stdClass PHP. :

class Foo{} 
$foo = new Foo(); 
echo ($foo instanceof stdClass)?'Yes':'No';

'N' stdClass "" , , . , PHP

0

PHP , . : .

-1

Source: https://habr.com/ru/post/1778709/


All Articles