Anurag Singh
Anurag Singh

Reputation: 727

Creating object in PHP of predefined class type

In this program i try to explore the Oops concept in PHP, but here the things are much different from java. in the sample program i have created an abstract class bird, class parrot which extends the bird class and an interface flyable. after that i included all the above class and interface in a php file. let have a look at the code

<?php
    include 'bird.php';
    include 'parrot.php';
    include 'flyable.php';

//creating a object
$bird1=new parrot();
echo $bird1->display();
echo("<br/>");
bird $bird2=new parrot();  //shows error

?> 

the thing i want to ask is that when i try to define the type of the object class like bird $bird1= new parrot(); at his line i get error but this thing works perfectly in java. please let me know how can i accomplish this thing in php.

Upvotes: 1

Views: 307

Answers (2)

hakre
hakre

Reputation: 198237

please let me know how can i accomplish this thing in php.

I'm not so well with Java, but from your pseudo code (the one that fails):

bird $bird2 = new parrot();

What you express here is that the variable $bird2 is of type bird. Variables in PHP are not strictly typed, therefore, there is not such a concept in PHP. Instead in PHP a variable can be of any type and it can change it, always. It can be even unset.

Now is this good or bad? Well, for your question it is bad, because what you did in Java is just not possible in PHP.

The general bad/good thing is a matter of taste and what not, so just learn about the language differences and try to make the best out of it.

BTW in PHP $bird2 is both a bird and a parrot, a way to check this is with instanceof and by using Type-Hinting.

Upvotes: 0

Jon Cairns
Jon Cairns

Reputation: 11949

You really should show the error, but it's bound to be due to the fact that you're using Java style type hinting on this line:

bird $bird2=new parrot();

Just remove the initial bird, as that's not valid syntax in PHP.

The only place where type hints are used in PHP are in method parameters. See the php docs for more information.

Upvotes: 4

Related Questions