How to declare abstract method in non-abstract class in PHP? - php

class absclass {
abstract public function fuc();
}
reports:
PHP Fatal error: Class absclass
contains 1 abstract method and must
therefore be declared abstract or
implement the remaining methods
(absclass::fuc)
I want to know what it means by implement the remaining methods,how?

See the chapter on Class Abstraction in the PHP manual:
PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature - they cannot define the implementation.
It means you either have to
abstract class absclass { // mark the entire class as abstract
abstract public function fuc();
}
or
class absclass {
public function fuc() { // implement the method body
// which means it won't be abstract anymore
};
}

I presume that remaining methods actually refers to the abstract methods you're trying to define (in this case, fuc()), since the non-abstract methods that might exist are okay anyway. It's probably an error message that could use a more precise wording: where it says remaining it could have said abstract.
The fix is pretty straightforward (that part of the error message is fine): you need to change this:
abstract public function fuc();
... into a proper implementation:
public function fuc(){
// Code comes here
}
... or, alternatively and depending your needs, make the whole class abstract:
abstract class absclass {
abstract public function fuc();
}

An abstract class cannot be directly instantiated, but it can contain both abstract and non-abstract methods.
If you extend an abstract class, you have to either implement all its abstract functions, or make the subclass abstract.
You cannot override a regular method and make it abstract, but you must (eventually) override all abstract methods and make them non-abstract.
<?php
abstract class Dog {
private $name = null;
private $gender = null;
public function __construct($name, $gender) {
$this->name = $name;
$this->gender = $gender;
}
public function getName() {return $this->name;}
public function setName($name) {$this->name = $name;}
public function getGender() {return $this->gender;}
public function setGender($gender) {$this->gender = $gender;}
abstract public function bark();
}
// non-abstract class inheritting from an abstract class - this one has to implement all inherited abstract methods.
class Daschund extends Dog {
public function bark() {
print "bowowwaoar" . PHP_EOL;
}
}
// this class causes a compilation error, because it fails to implement bark().
class BadDog extends Dog {
// boom! where's bark() ?
}
// this one succeeds in compiling,
// it's passing the buck of implementing it's inheritted abstract methods on to sub classes.
abstract class PassTheBuckDog extends Dog {
// no boom. only non-abstract subclasses have to bark().
}
$dog = new Daschund('Fred', 'male');
$dog->setGender('female');
print "name: " . $dog->getName() . PHP_EOL;
print "gender: ". $dog->getGender() . PHP_EOL;
$dog->bark();
?>
That program bombs with:
PHP Fatal error: Class BadDog
contains 1 abstract method and must
therefore be declared abstract or
implement the remaining methods
(Dog::bark)
If you comment out the BadDog class, then the output is:
name: Fred
gender: female
bowowwaoar
If you try to instantiate a Dog or a PassTheBuckDog directly, like this:
$wrong = new Dog('somma','it');
$bad = new PassTheBuckDog('phamous','monster');
..it bombs with:
PHP Fatal error: Cannot instantiate
abstract class Dog
or (if you comment out the $wrong line)
PHP Fatal error: Cannot instantiate
abstract class PassTheBuckDog
You can, however, call a static function of an abstract class:
abstract class Dog {
..
public static function getBarker($classname, $name, $gender) {
return new $classname($name, $gender);
}
..
}
..
$other_dog = Dog::getBarker('Daschund', 'Wilma', 'female');
$other_dog->bark();
That works just fine.

You're being slightly led astray by this error message. In this case, since it is within this class that fuc is being defined, it wouldn't really make sense to implement it in this class. What the error is trying to tell you is that a non-abstract class cannot have abstract methods. As soon as you put an abstract method in the definition of a class, you must also mark the class itself as abstract.

Abstract keywords are used to label classes or methods as patterns. It's similar to interfaces but can contain variables and implementations of methods.
There are a lot of misunderstandings concerning abstract classes. Here is an example of an abstract Dog class. If a developer wants to create some basic Dog class for other developers or for himself to extend he declares the class as abstract. You can't instantiate the Dog class directly (nobody can), but you can extend Dog by your own class. SmartDog extends Dog etc.
All methods that are declared to be abstract by the Dog class must be implemented manually in each class that extends Dog.
For example, the abstract class Dog has an abstract method Dog::Bark(). But all Dogs bark differently. So in each Dog-subclasses you must describe HOW that dog barks concretely, so you must define eg SmartDog::Bark().

It means that the proper of an abstract class is having at least one abstract method. So your class has either to implement the method (non abstract), or to be declared abstract.

I wanted to use an abstract method within a non-abstract class (normal class?) and found that I could wrap the method's contents in an 'if' statement with get_parent_class() like so:
if (get_parent_class($this) !== false) {
Or, in action (tested in a file on cmd line: php -f "abstract_method_normal_class_test.php"):
<?php
class dad {
function dad() {
if (get_parent_class($this) !== false) {
// implements some logic
echo "I'm " , get_class($this) , "\n";
} else {
echo "I'm " , get_class($this) , "\n";
}
}
}
class child extends dad {
function child() {
parent::dad();
}
}
$foo = new dad();
$bar = new child();
?>
Output:
I'm dad
I'm child
PHP get_parent_class() Documentation

Related

PHP: Fatal error: Cannot instantiate abstract class

I have an abstract database class named as:
abstract class database {
protected $value;
}
I created another abstract class
abstract class my_database extends database {
public function set_value($value) {
$this->value = $value;
}
}
When I try to use it:
$my_db = new my_database();
I get error:
Fatal error: Cannot instantiate abstract class my_database in ...
What I try to do is: The abstract class database has a protected $value and I would like to create a wrapper class, to be able to change the protected value (temporarily).
How can I do that?
EDIT1: unfortunately earlier, when I tried without abstract my_database, I got the errors:
- abstract methods and must therefore be declared abstract or implemented
- Abstract function cannot contain body
EDIT2:
After taking out the abstract word completely from my_database, I got the following error:
Fatal error: Class my_database contains 32 abstract methods and must
therefore be declared abstract or implement the remaining methods
How can I fix this?
Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. You can read about this in PHP's documentation here: link
Here's an example.
There is an abstract class (note that abstract methods don't have body - they CAN'T have body - it's just a signature):
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method. It will be available for all children - they don't have to declare it again.
public function printOut() {
print $this->getValue() . "\n";
}
}
Extend your abstract class with a class like this (note that all abstract methods MUST be defined in concrete class):
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
Then you can create instance of ConcreteClass1:
$class1 = new ConcreteClass1;
Your class should not be abstract:
class my_database extends database {
public function set_value($value) {
$this->value = $value;
}
}
In OOP, abstract class can't be instanciated juste it can be extended.

Calling a child class function if not exist in parent class

I have a code like following ---
class CartItem{
var $v;
function __construct(){
$this->f();
}
function f(){
echo 'In parent';
}
}
class m extends CartItem{
function f(){
echo 'In child';
}
}
new m();
Now when creating instance of m()... it doesn't have any constructor, so it is calling parent classes constructor. Now inside that a function f is called.
What I want is -
if class m() have defined function f()... is should call it instead of parent class's function f().
But anyway it is calling parent classes function, as it was called from parent's constructor, irrespective of child class/ context :(
You want to call in __construct() a method that is not defined in the class. This is a sign that the CartItem class is an abstract concept and you don't intend to instantiate it (because an instance of CartItem probably doesn't contain enough information or behaviour for your project).
An abstract concept is implemented using an abstract class that defines as much as it can and defines abstract methods to be implemented in the concrete classes that extend it. The method f() is such a method that cannot be defined in the abstract concept and has to be defined in each class that extend it:
abstract class CartItem
{
public function __construct()
{
$this->f();
}
abstract protected function f();
}
class m extends CartItem
{
protected function f()
{
// Implement behaviour specific to this class
}
}
This is actually a really interesting question.
so, as I understand it, you're asking (if this isnt right please say):
can you call a function of a class that's extending a parent?
yes, you can... sort of, if the method in the child is static.
Take this example (Ive not used it in the constructor for simplicity of example, but it will work there too):
class ClassA {
public function testMeAsWell() {
return ClassB::testMe();
}
}
class ClassB extends ClassA {
static function testMe() {
return 'do something';
}
}
$child = new ClassB();
echo $child->testMe();
// outputs 'do something'
$parent = new ClassA();
echo $parent->testMeAsWell();
// also outputs 'do something'
the reason this works needs more research, but as a guess I would say that because PHP is compiled, it will know about both classes at run-time and therefore will be able to figure out what we wanted it to do.
So, further on, you want to use variables. Yes you can, but they would have to be static as well.
working example

Analyze abstract class in php

i have become a bit confused about abstract class ! i have read more of the post written in stackoverflow and another website but i didn't understand ! so i took a look at my book again but i didn't understand it either . so please analyze the code below step by step :
thanks in advance
<?php
abstract class AbstractClass
{
abstract protected function getValue();
public function printOut() {
print $this->getValue();
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
}
class ConcreteClass2 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass2";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
$class2 = new ConcreteClass2;
$class2->printOut();
?>
By definition
'An abstract class is a class that is declared abstract —it may or may
not include abstract methods. Abstract classes cannot be instantiated,
but they can be subclassed. An abstract method is a method that is
declared without an implementation'.
If defined an abstract class, you should extend that class with another.
In case of having abstract methods within the abstract class, you should write them in the child class in order to instantiate the child.
Related to the code, that is why when you instantiate the ConcreteClass, the getValue function is 'overwritten' to the pattern, while calling to the printOut method is from the father itself, because It is already written and not overwritten by the child. (See also that method was not abstract, that is why you can also use it from the father class)
Your code is right. Abstact class mean, when you can not make a instance of it. You can not do this:
$abstract = new AbstractClass();

Overriding methods in PHP?

In other OO languages like Java we can override a function, possible using keywords/annotations like implements, #override etc.
Is there a way to do so in PHP? I mean, for example:
class myClass {
public static function reImplmentThis() { //this method should be overriden by user
}
}
I want user to implement their own myClass::reImplementThis() method.
How can I do that in PHP? If it is possible, can I make it optional?
I mean, if the user is not implementing the method, can I specify a default method or can I identify that the method is not defined (can I do this using method_exists)?
<?php
abstract class Test
{
abstract protected function test();
protected function anotherTest() {
}
}
class TestTest extends Test
{
protected function test() {
}
}
$test = new TestTest();
?>
This way the class TestTest must override the function test.
Yes, there is. You have the option to override a method by extending the class and defining a method with the same name, function signature and access specifier (either public or protected) it had in the base class. The method should not be declared abstract in the base class or you will be required to implement it in the derived class. In you example it would look something like this:
class MyClass {
public static function reImplmentThis() { //this method should be overriden by user
}
}
class MyDerivedClass extends MyClass {
public static function reImplmentThis() { //the method you want to call
}
}
If the user does not overrides it, MyDerivedClass will still have a reImplmentThis() method, the one inherited from MyClass.
That said, you need to be very careful when invoking extended static methods from your derived class to stay out of trouble. I encourage you to refactor your code to extend instance methods unless you have a very specific need to extend static classes. And if you decide there is no better way than extending static classes please be sure to understand Late Static Binding pretty well.
Yes, its possible to check if the method is implemented or not and get a whole lot more of information about a class using PHP Reflection.
This touches on several OOP subjects.
First, simply overriding an method declared in a parent class is as simple as re-declaring the method in an inheriting class.
E.g:
class Person {
public function greet(string $whom) {
echo "hello $whom!";
}
}
class Tommy extends Person {
public function greet(string $whom = "everyone") {
echo "Howdy $whom! How are you?";
}
}
$a = new Tommy();
$a->greet('World');
// outputs:
// Howdy World! How are you?
If on the overriding method you wan to reuse the logic of the overriden one, it's just a matter of calling the parent's method from the extending class::
class Tommy
{
public function greet(string $whom)
{
// now with more emphasis!!!
echo parent::greet(strtoupper($whom)) . "!!!!";
}
}
Now Tommy::greet() calls Person::greet(), but modifies the result before returning it.
One thing to note is that overriding methods have to be compatible with the overriden one: the method visibility can't be more restrictive than the original one (it's OK to increase visibility), and the number and type of required arguments can't conflict with the original delcaration.
This works, because the type of the arguments does not clash with the original, and we have less required arguments than on the parent:
class Leo extends Person {
public function greet(string $whom = "gorgeous", string $greet = "Whatsup" ) {
echo "$greet $whom. How are you?";
}
}
But this doesn't, since there are additional required arguments. This would make impossible to switch the original class for this one transparently, and thus would throw a Warning:
class BadBob extends Person {
public function greet(string $whom, string $greet ) {
echo "$greet $whom. How are you?";
}
}
Additionally, you mention in your question that "this method should be overriden by the user". If you require client classes to actually implement the method, you have a couple of options:
Abstract classes & methods
These are methods where the implementation is left empty, and that extending classes have to implement to be valid. In we changed our original class Person to:
abstract class Person {
public function greet(string $whom) {
echo "hello $whom!";
}
public abstract function hide();
}
Since now the class contains an abstract method, it needs to be declared as an abstract class as well.
Now it is not possible to instantiate Person directly, you can only extend it in other classes.
Now all our existing Person extending classes would be wrong, and trying to execute the previous code would throw a fatal error.
An example of a valid class extending Person now would be:
class Archie extends Person {
public function hide() {
echo "Hides behind a bush";
}
}
Any class that extends Person must declare a public hide() method.
Interfaces
Finally, you mention interfaces. Interfaces are contracts that implementing classes have to fulfill. They declare a group of public methods without an implementation body.
E.g.:
interface Policeman {
public function arrest(Person $person) : bool;
public function help($what): bool;
}
Now we could have class that extended Person and implemented Policeman:
class Jane extends Person implements Policeman {
public function hide() {
echo "Jane hides in her patrol-car";
}
public function arrest(Person $person): bool{
// implement arrest method
return false;
}
public function shoot($what): bool {
// implements shoot() method
return false;
}
}
Importantly, while it's possible to extend only one class (there is no multiple inheritance in PHP), it is possible to implement multiple interfaces, and the requirements for each of those have to be fulfilled for the class to be valid.

What is an abstract class in PHP?

What is an abstract class in PHP?
How can it be used?
An abstract class is a class that contains at least one abstract method, which is a method without any actual code in it, just the name and the parameters, and that has been marked as "abstract".
The purpose of this is to provide a kind of template to inherit from and to force the inheriting class to implement the abstract methods.
An abstract class thus is something between a regular class and a pure interface. Also interfaces are a special case of abstract classes where ALL methods are abstract.
See this section of the PHP manual for further reference.
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
1. Can not instantiate abstract class: Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract.
Example below :
abstract class AbstractClass
{
abstract protected function getValue();
abstract protected function prefixValue($prefix);
public function printOut() {
echo "Hello how are you?";
}
}
$obj=new AbstractClass();
$obj->printOut();
//Fatal error: Cannot instantiate abstract class AbstractClass
2. Any class that contains at least one abstract method must also be abstract: Abstract class can have abstract and non-abstract methods, but it must contain at least one abstract method. If a class has at least one abstract method, then the class must be declared abstract.
Note: Traits support the use of abstract methods in order to impose requirements upon the exhibiting class.
Example below :
class Non_Abstract_Class
{
abstract protected function getValue();
public function printOut() {
echo "Hello how are you?";
}
}
$obj=new Non_Abstract_Class();
$obj->printOut();
//Fatal error: Class Non_Abstract_Class contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Non_Abstract_Class::getValue)
3. An abstract method can not contain body: Methods defined as abstract simply declare the method's signature - they cannot define the implementation. But a non-abstract method can define the implementation.
abstract class AbstractClass
{
abstract protected function getValue(){
return "Hello how are you?";
}
public function printOut() {
echo $this->getValue() . "\n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";
//Fatal error: Abstract function AbstractClass::getValue() cannot contain body
4. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child :If you inherit an abstract class you have to provide implementations to all the abstract methods in it.
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
// Common method
public function printOut() {
print $this->getValue() . "<br/>";
}
}
class ConcreteClass1 extends AbstractClass
{
public function printOut() {
echo "dhairya";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
//Fatal error: Class ConcreteClass1 contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (AbstractClass::getValue)
5. Same (or a less restricted) visibility:When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
Note that abstract method should not be private.
abstract class AbstractClass
{
abstract public function getValue();
abstract protected function prefixValue($prefix);
public function printOut() {
print $this->getValue();
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."<br/>";
//Fatal error: Access level to ConcreteClass1::getValue() must be public (as in class AbstractClass)
6. Signatures of the abstract methods must match:When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child;the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature.
abstract class AbstractClass
{
abstract protected function prefixName($name);
}
class ConcreteClass extends AbstractClass
{
public function prefixName($name, $separator = ".") {
if ($name == "Pacman") {
$prefix = "Mr";
} elseif ($name == "Pacwoman") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$prefix}{$separator} {$name}";
}
}
$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "<br/>";
echo $class->prefixName("Pacwoman"), "<br/>";
//output: Mr. Pacman
// Mrs. Pacwoman
7. Abstract class doesn't support multiple inheritance:Abstract class can extends another abstract class,Abstract class can provide the implementation of interface.But it doesn't support multiple inheritance.
interface MyInterface{
public function foo();
public function bar();
}
abstract class MyAbstract1{
abstract public function baz();
}
abstract class MyAbstract2 extends MyAbstract1 implements MyInterface{
public function foo(){ echo "foo"; }
public function bar(){ echo "bar"; }
public function baz(){ echo "baz"; }
}
class MyClass extends MyAbstract2{
}
$obj=new MyClass;
$obj->foo();
$obj->bar();
$obj->baz();
//output: foobarbaz
Note: Please note order or positioning of the classes in your code can affect the interpreter and can cause a Fatal error.
So, when using multiple levels of abstraction, be careful of the positioning of the classes within the source code.
below example will cause Fatal error: Class 'horse' not found
class cart extends horse {
public function get_breed() { return "Wood"; }
}
abstract class horse extends animal {
public function get_breed() { return "Jersey"; }
}
abstract class animal {
public abstract function get_breed();
}
$cart = new cart();
print($cart->get_breed());
An abstract class is a class that is
only partially implemented by the
programmer. It may contain one or more
abstract methods. An abstract method
is simply a function definition that
serves to tell the programmer that the
method must be implemented in a child
class.
There is good explanation of that here.
Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes
Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class
Example Code:
abstract class A {
public function test1() {
echo 'Hello World';
}
abstract protected function f1();
abstract public function f2();
protected function test2(){
echo 'Hello World test';
}
}
class B extends A {
public $a = 'India';
public function f1() {
echo "F1 Method Call";
}
public function f2() {
echo "F2 Method Call";
}
}
$b = new B();
echo $b->test1() . "<br/>";
echo $b->a . "<br/>";
echo $b->test2() . "<br/>";
echo $b->f1() . "<br/>";
echo $b->f2() . "<br/>";
Output:
Hello World
India
Hello World test
F1 Method Call
F2 Method Call
Abstract Class contains only declare the method's signature, they can't define the implementation.
Abstraction class are defined using the keyword abstract .
Abstract Class is not possible to implement multiple inheritance.
Latest version of PHP 5 has introduces abstract classes and methods.
Classes defined as abstract , we are unable to create the object ( may not instantiated )
An abstract class is like the normal class it contains variables it contains protected variables functions it contains constructor only one thing is different it contains abstract method.
The abstract method means an empty method without definition so only one difference in abstract class we can not create an object of abstract class
Abstract must contains the abstract method and those methods must be defined in its inheriting class.

Categories