Bakalash
Bakalash

Reputation: 553

get type in php returns "object" and not the object type

im trying to get the type of the object that i receive in the constructor using gettype($this->object) . but im only getting "object" my constructor: p

public function __construct($object=null)
    {
        $this->object=$object;

    }

the object that i send to class:

$campaign = new Campaign();

$type = new Nodes\CampaignDatabaseNode($campaign);
$type->checkType();

the checkType(); only echo the type of the object

Upvotes: 25

Views: 38321

Answers (4)

evilReiko
evilReiko

Reputation: 20473

gettype($obj);// Output: "object"
$obj instanceof Myclass;// Output: true (if it's an instance of that class)

gettype() returns the type of variable, like "string", "integer", "array", etc.

instanceof checks whether object is instance of that specified class.

Upvotes: 11

madsen
madsen

Reputation: 462

Just to explain why gettype() doesn't work as expected since others have already provided the correct answer. gettype() returns the type of variable — i.e. boolean, integer, double, string, array, object, resource, NULL or unknown type (cf. the gettype() manual link above).

In your case the variable $campaign is an object (as returned by gettype()), and that object is an instance of the class Campaign (as returned by get_class()).

Upvotes: 31

Dale
Dale

Reputation: 10469

You can use get_class($object);

http://www.php.net/get_class

To help with your new situation (if I've understood properly)

<?php

namespace Ridiculous\Test\Whatever;

class example {}

$example = new example();

echo get_class($example) . '<br>';
echo basename(get_class($example)); // this may be what you're after

Upvotes: 16

user2655603
user2655603

Reputation: 410

1 In order to get the type of the object, use the function get_class() - http://php.net/manual/en/function.get-class.php .

2 In order to prevent invalid object passing, you can typehint the argument class, like the following:

public function __construct(Campaign $object=null)
{
    $this->object=$object;
}

Upvotes: 1

Related Questions