PHP OOPs perguntas e respostas de entrevista
Pergunta 21. What is composition in OOP?
Composition is a way of creating complex objects by combining simpler objects or classes. It involves creating relationships between objects rather than relying on inheritance.
Example:
class Engine {
/* Engine properties and methods */
}
class Car {
private $engine;
public function __construct(Engine $engine) {
$this->engine = $engine;
}
}
Pergunta 22. Explain the difference between private, protected, and public visibility in PHP.
Private members are only accessible within the class, protected members are accessible within the class and its subclasses, and public members are accessible from outside the class.
Example:
class Example {
private $privateVar;
protected $protectedVar;
public $publicVar;
}
Pergunta 23. What is method chaining in PHP?
Method chaining is a technique where multiple methods can be called on the same object in a single line. It improves code readability and conciseness.
Example:
class Calculator {
private $result;
public function add($a, $b) {
$this->result = $a + $b;
return $this;
}
public function multiply($a) {
$this->result *= $a;
return $this;
}
}
$total = (new Calculator())->add(3, 5)->multiply(2)->getResult();
Pergunta 24. What is the purpose of the 'namespace' keyword in PHP?
Namespaces are used to avoid naming conflicts between classes, functions, and constants. They provide a way to organize code into logical and hierarchical structures.
Example:
namespace MyNamespace;
class MyClass { /* class definition */ }
Pergunta 25. Explain the concept of dependency injection.
Dependency injection is a design pattern where the dependencies of a class are injected from the outside rather than created within the class. It promotes loose coupling and testability.
Example:
class Database {
/* database operations */
}
class UserRepository {
private $database;
public function __construct(Database $database) {
$this->database = $database;
}
}
Mais uteis segundo os usuarios:
- What is Object-Oriented Programming (OOP)?
- Explain the four pillars of OOP.
- How does inheritance work in PHP?