John Smith
John Smith

Reputation: 6197

Php, type cast (downcast) (getting rid of extended class)

I know PhP has no something like typecast, but lets give a try. I have an entity:

class Entity extends Base
{
    private $name;

    public function getName()
    {
        return $this->name;
    }

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

and its Base

abstract class Base
{
    public function save()
    {
    }
}

now there is an Entity:

$e = new Entity();

and I can pass it to a method:

$this->callMe($e);

private function callMe (Entity $e)
{
    $e->getName(); // OK!
    $e->save();  // !!!!!!!!!!!! I DONT WANT IT
}

the problem is, I only want to pass the Entity itself, and skip the inherited properties. Simply because I dont want somebody mess with other routines. Of course, I can do something like:

// problem is too many parameters and not tight coupled enough
$this->callMe($e->getName(), $e->getWhatever());

or

// then no longer type hinting, just a "bag" array
$this->callMe($e->toArray());

in other words, I want to get rid of inherited class.

Upvotes: 0

Views: 544

Answers (2)

iLikeBreakfast
iLikeBreakfast

Reputation: 1555

As @zerkms said, if you don't want it, don't do it.

If you have some odd use case, consider using Reflection http://php.net/manual/en/reflectionclass.getmethods.php

Here's some example

<?php

class Entity extends Base
{
    private $name;

    public function getName()
    {
        return $this->name;
    }

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

abstract class Base
{
    public function save()
    {
    }
}

$test = new Entity();

$reflectionClass = new ReflectionClass($test);
$methods = $reflectionClass->getMethods();
var_dump($methods);

The $methods variable will have $class references, as you'll see in this output. Use that to only call methods from class Entity.

Upvotes: 3

Rafi
Rafi

Reputation: 489

If you don't want to give access to some inherited methods simply make them private or protected in your base class.

Upvotes: 1

Related Questions