2

Consider below code :

<?php
  trait HelloWorld {
    public function sayHello() {
      echo 'Hello World!';
    }
  }

  // Change visibility of sayHello
  class MyClass1 {
    use HelloWorld { sayHello as protected; }
  }

  // Alias method with changed visibility
  // sayHello visibility not changed
  class MyClass2 {
    use HelloWorld { sayHello as private myPrivateHello; }
  }
?>

How should I access the method sayHello() after changing its visibility either withing the current class as the new visibility has been set to protected in one class and set to private in another class with an alias?

How to access the public method sayHello() with the object of some class defined in the trait?

The term "Exhibiting Class" has been used in the PHP manual. Someone please explain what this term "Exhibiting Class" means which class?

tereško
  • 58,060
  • 25
  • 98
  • 150
PHPLover
  • 1
  • 51
  • 158
  • 311
  • You can't change visibility, as the compiler copies and pastes the trait code into your class. So there is no inheritance to which you can overload a method. You'd have to go for a different solution. – Code4R7 Nov 22 '17 at 09:15
  • The exhibiting class essentially refers to the class that is used, this would be `MyClass1` and `MyClass2` respectively. Essentially it sets the visibillity for the function only on the class where it is specified. I.e if we take `MyClass1` and change `sayHello` to `protected` it will not affect `MyClass2`. Atleast that's how I understand it - please correct me if I am wrong, i'm quite interested in this topic aswell. – Classified Nov 22 '17 at 09:24
  • @tereško I think the link was meant for Code4R7? :) – Classified Nov 22 '17 at 09:44
  • @Code4R7 yes, you can https://php.net/manual/en/language.oop5.traits.php#language.oop5.traits.visibility .. the OP apparently is unable to actually try and play with the example in the php documentation and instead keeps asking people to spoonfeed him. – tereško Nov 22 '17 at 09:56
  • @tereško : My question is specifically related to the concept of "Traits" so, it can't be marked as duplicate. The link of question you provided doesn't clear my doubts. Please remove the Duplicate mark so that people can answer my doubts. Thank You. – PHPLover Nov 22 '17 at 10:05
  • No, because it is a duplicate of the marked question. – tereško Nov 22 '17 at 19:36

0 Answers0