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
https://forums.phpfreaks.com/topic/261873-oop-php-functions/
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
https://forums.phpfreaks.com/topic/261873-oop-php-functions/#findComment-1341833
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.