CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2009
    Posts
    160

    a few questions on classes/ objects

    1. Can i initialize an object of another class in a class eg

    Code:
    class db {
    public function connect() {  ------ }
    ........... }
    
    class user {
    
    public $name;
    
    $obj=new db();
    
    }
    and then use the above like
    Code:
    $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?

  2. #2
    Join Date
    May 2002
    Posts
    10,943

    Re: a few questions on classes/ objects

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

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

    $b = new b();
    $b->test();
    ?>
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  3. #3
    Join Date
    May 2009
    Posts
    160

    Re: a few questions on classes/ objects

    Quote Originally Posted by PeejAvery View Post
    PHP Code:
    <?php
    class {
      function 
    test() {
        echo 
    'Function "test" executed from Class a<br />';
      }
    }

    class 
    {
      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();

  4. #4
    Join Date
    May 2002
    Posts
    10,943

    Re: a few questions on classes/ objects

    No, you don't have to use it with scope. You can create a new object instance.

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

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

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

    $b = new b();
    $b->test();
    ?>
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured