1

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.

2
  • 2
    You can not specify the type of a variable in PHP. Commented Aug 7, 2013 at 11:00
  • 1
    If parrot or bird implements flyable then surely you have the includes in the wrong order. Commented Aug 7, 2013 at 11:00

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well, it's a parrot. You can use get_class($bird2) to get the class name of an object. PHP is similar to Java in some ways, but it's less strict about enforcing types. In Java, you have to declare the type of everything as you pass it around, but that's not the case with PHP. Even the cases where you can use type hinting (see the link in the answer) are optional.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.