Page 1 of 1

basic code help.

Posted: Sat Jun 27, 2009 11:07 am
by gimpact
Hi,
I have recently migrated from servlets to php, can you please help me to understand few basic concept of OOPs?

Lets assume that

Code: Select all

<?php
class A
private $name;
{
    function name($name){
     print $name;
     }
}
 
class B
{
    function bar()
    {
       // Help here!
    }
}
1. How do I include another class?
a> include "A.php";
2. How do I create an instance of class A in class B?
a> $a -> new B;
3. How do I call function name() of class A?
a> $a->name();
4. How do I assign value to name() of class A?
a> $a -> name("gimpact");

Please correct me if I am wrong. I am learning from the web but some times you know some things are not very clear.

Thank you

Re: basic code help.

Posted: Sat Jun 27, 2009 11:36 am
by McInfo
A.class.php -- The name() method acts as both a getter and setter.

Code: Select all

<?php
class A
{
    private $name;
   
    public function __construct ()
    {
        $this->name = 'Default Name';
    }
   
    public function name ($name = null)
    {
        if (!is_null($name)) {
            $this->name = $name;
        }
        return $this->name;
    }
}
?>
B1.class.php -- Creates an instance of A in B1.

Code: Select all

<?php
include_once 'A.class.php';
class B1
{
    public $a;
   
    public function __construct ()
    {
        $this->a = new A();
    }
}
?>
B2.class.php -- B2 extends A. A is B2's parent. B2 is a child of A.

Code: Select all

<?php
include_once 'A.class.php';
class B2 extends A
{
}
?>
usage.php

Code: Select all

<?php
include_once 'B1.class.php';
$b1 = new B1();
echo $b1->a->name('B1 Alpha'); // B1 Alpha
 
include_once 'B2.class.php';
$b2 = new B2();
echo $b2->name(); // Default Name
echo $b2->name('B2 Alpha'); // B2 Alpha
?>
PHP Manual: Classes and Objects, The Basics

Edit: This post was recovered from search engine cache.

Re: basic code help.

Posted: Sat Jun 27, 2009 7:19 pm
by gimpact
Thank you.