Jump to content

OOP php functions


Bryce910

Recommended Posts

When in OOP I have been watching tutorials and some have functions just written like

 class user
{
public $user;

public function __construct($u)
{
   $this->user = $u;
}

}

 

do I need to type public before the function or is it better practice to just put

 

class user
{
public $user;

function __construct($u)
{
   $this->user = $u;
}

}

 

Thanks!

Link to comment
Share on other sites

Functions are public without any cast.

 

class A {
    public $user;
    
    public function __construct(){
        $this->user = 'apple';
    }
    
    function getApple(){
        return $this->user;
    }
}

class B {
    public $user;
    
    public function __construct(){
        $a = new A();
        $this->user = 'b' . $a->getApple();
    }
    
    function getApple(){
        return $this->user;
    }
}

$b = new B;
echo $b->getApple();

 

This code would return bapple.

 

If the getApple() method in A was private, B would not be able to access A's getApple() method. However, if A's getApple() method was protected, and class B extends A, then you would be able to access A's getApple() method.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.