Usman Waheed
Usman Waheed

Reputation: 78

How can i get output in oop program in php

This is my code. It is giving me an error. I am new in OOP in PHP, please help me regarding this particular issue.

Code as following:

<?php 
class myclass 
{
   var $name;
   //public $vari="this is my class ";
   public function setvalue($newval)
   {
       $this->$name=$newval;
   }
   public function getvalue()
   {
       return $this->name;

   }
}

$object= new myclaas;
$object->setvalue("usman");
echo $object->getvalue();
?>

Error as following:

Fatal error: Class 'myclaas' not found in E:\wamp\www\oops\myclass.php on line 19

Upvotes: 1

Views: 52

Answers (2)

Harish Lalwani
Harish Lalwani

Reputation: 774

Final edit -

class myclass 
{
 var $name;

public function setvalue($newval)
{
   $this->name=$newval;      //variable calling was incorrect
}
public function getvalue()
{
   return $this->name;
}
}



$object= new myclass;    //class name correction
$object->setvalue("usman");
echo $object->getvalue();

Upvotes: 1

Jijo John
Jijo John

Reputation: 1375

These are the two errors in your code. You didn't type the class name properly when you instantiated the class.Your class name is myclass , But you typed the class name myclaas.

Your Code

 $object= new myclaas;

See the corrected line below.

 $object= new myclass;

When you access properties in a class using $this pseudo variable don't insert a dollar sign in front of the variable (In your code see the $ sign in $name , You don't need it).

Your code look like this

 $this->$name = $newval;

You need to change the code to

 $this->name = $newval;

Updated code

<?php 
class myclass 
{
   var $name;

   public function setvalue($newval)
   {
       $this->name=$newval;
   }
   public function getvalue()
   {
       return $this->name;

   }
}

$object= new myclass;
$object->setvalue("usman");
echo $object->getvalue();
?>

Thanks and Have a good one :)

Upvotes: 2

Related Questions