/    Sign up×
Community /Pin to ProfileBookmark

Typecasting Objects

Can I typecast variables to particular kinds of objects? For example:

[code]class Shape {}
class Circle extends Shape {}
$o = new Circle();

// From here on out, $o should be an instance of Shape as far as PHP is concerned
$o = (Shape)$o;[/code]

The only solution I’ve found so far is to serialize the object, manipulate the string, then unserialize. But this seems less than ideal. Is there a better way?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiJul 02.2009 — If Circle extends Shape, then $o is already an instance of Shape as far as PHP is concerned.

[code=php]
class Shape {}
class Circle extends Shape {}
$o = new Circle();
var_dump($o instanceof Shape); // bool(true)
[/code]
Copy linkTweet thisAlerts:
@Jeff_MottauthorJul 02.2009 — Because I'm caching objects. If I cast a Circle object to a Shape and then cache it, then in another script invocation when I load the cache and restore the object, I can skip loading all the Shape subclasses.

So that's the why. Do you have any suggestions [i]how[/i] to do this?
Copy linkTweet thisAlerts:
@Jeff_MottauthorJul 02.2009 — Perhaps my words were a bit murky. I want to cast an object such that...

class Shape {}
class Circle extends Shape {}
$o = new Circle();

$o = (Shape)$o;
get_class($o) == 'Shape'; [color=green]// <-- I want this to be true; PHP should think it's of class Shape[/color]
×

Success!

Help @Jeff_Mott spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...