Click to See Complete Forum and Search --> : a few questions on classes/ objects


niladhar8@gmail.com
September 18th, 2009, 10:27 AM
1. Can i initialize an object of another class in a class eg



class db {
public function connect() { ------ }
........... }

class user {

public $name;

$obj=new db();

}


and then use the above like

$user = new user();
$user->obj->connect();




2. If i have two classes A and B how can i call functions of class A withing class B?

PeejAvery
September 18th, 2009, 10:54 AM
<?php
class a {
function test() {
echo 'Function "test" executed from Class a<br />';
}
}

class b {
function test() {
echo 'Function "test" executed from Class b<br />';
a::test();
}
}

$b = new b();
$b->test();
?>

niladhar8@gmail.com
September 18th, 2009, 11:07 AM
<?php
class a {
function test() {
echo 'Function "test" executed from Class a<br />';
}
}

class b {
function test() {
echo 'Function "test" executed from Class b<br />';
a::test();
}
}

$b = new b();
$b->test();
?>

Can i initialize an object instead of using the scope resolution operator to call class a's test function. ( whats the term for doing what you have done - using scopre resolution to call a test).

how would i call a::test() using an object of type b.

would this result to an error in php $obj->db->connect();

PeejAvery
September 18th, 2009, 01:02 PM
No, you don't have to use it with scope. You can create a new object instance.

<?php
class a {
function test() {
echo 'Function "test" executed from Class a<br />';
}
}

class b {
function test() {
echo 'Function "test" executed from Class b<br />';
//a::test();

$a = new a();
$a->test();
}
}

$b = new b();
$b->test();
?>