#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    29
    Rep Power
    0

    How to use in the other function the variable in function


    hi,

    PHP Code:

    <?php 

    class index 
        

            function 
    foo()
                {
                    
                    
    $val="bar";
                    
                    
                }
                
    }

            class 
    index2 extends index 
            
                    function 
    bar ()
                        {
                            
                            echo 
    $val;
                            
                        }
                        
            }
                
            

    $dir=new index2();
    echo 
    $dir->bar();

    ?>

    variable in that foo method, I want to use in class of bar method being extends

    but it does not work...

    how to use?
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,920
    Rep Power
    1045
    Hi,

    this doesn't make sense. First of all, $val is a local variable. It isn't visible anywhere except for this specific function while it's running. I guess what you actually want is an attribute. Secondly, even if this was an attribute, you'd need to call foo() to even set the attribute to "bar". Before you'll just get null.

    I think you should look into the OOP basics again. A working example would be

    PHP Code:
    <?php

    class {

        public 
    $var 'bar';

    }

    class 
    extends {

        public function 
    bar() {
            echo 
    $this->var;
        }

    }

    $a = new B();
    $a->bar();
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    29
    Rep Power
    0
    thanks jacguies

    I suppose that I dont know the php classes...like that you said, I should work this about.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2011
    Posts
    140
    Rep Power
    0

    Find the solutions of your problem.


    Hi Friend

    Please find the Solutions of your problem.

    [PHPNET=""]<?php
    class index {
    function foo()
    {
    echo $val="bar";

    }
    }
    class index2 extends index {
    function bar ()
    {
    $this-> foo(); // call foo() method inside bar()

    }
    }

    $dir=new index2();
    $dir->bar();
    ?>
    O/P:- bar
    [/PHPNET]

    Comments on this post

    • Jacques1 disagrees : Dear friend, please stop posting useless "solutions" and learn to use code tags (after 1 1/2 years and 100 posts).

IMN logo majestic logo threadwatch logo seochat tools logo