r/PHPhelp • • Mar 23 '23

PHP vs Python

PHP and Python are popular programming languages but have different strengths and weaknesses. So which one should I choose from?

0 Upvotes

18 comments sorted by

View all comments

2

u/equilni Mar 25 '23

You are asking in a PHP forum, so of course the answer is PHP. Honestly, like others have noted, it depends on what you are doing.

but have different strengths and weaknesses

If I recall correctly, PHP's OOP is more verbose than Python.

Classes:

PHP:
class Noun {
    private string $Attribute = '';

    public function Verb(): string {
        return $this->Attribute;
    }
}
$noun = new Noun();
echo $noun->Verb();

Python:
class Noun:
    Attribute = '' 

    def Verb(self):   #python passes self to methods, except for static
        return self.Attribute

noun = Noun()
print(noun.Verb())

Visibility. If I recall for Python, it's just a naming convention, not enforced by the system.

PHP
Public 	    = public $name
Protected 	= protected $name
Private 	= private $name

Python
Public 	    = name
Protected 	= _name (single underscore)
Private 	= __name (double underscore)

Static methods:

# PHP
class Test {
    public static function welcomeMessage() {
        return 'Welcome!';
    }
}

echo Test::welcomeMessage();

# Python
class Test:
    @staticmethod
    def welcomeMessage(): # don't have to pass self
        return 'Welcome!'

print(Test.welcomeMessage())

Inheritance. Python reminds me of using DI in PHP, which isn't that far off...

# PHP
Class Test {}
Class Test2 extends Test {}

# Python
class Test
class Test2(Test)

Multiple inheritance. Again, Python acts like DI with PHP.

PHP - Cannot be done.  Use Traits
trait Test1 {}
trait Test2 {}

class TestOne {}

class TestTwo extends TestOne {
    use Test1, Test2;
}

Python
class One:
    os = 'Mac OS'

class Two:
    brand = 'Apple'

class Three(One, Two):
    def __init__(self):
        print(self.os) # Mac OS