I am learning php now using code academy website but some is not explained properly.
These are the conditions:
Create a class called Cat.
Add two public properties to this class: $isAlive ought to store the value true and $numLegs should contain the value 4.
Add a public $name property, which gets its value via the __construct() or.
Add a public method called meow(), which returns "Meow meow".
Create an instance of the Cat class, which has the $name "CodeCat".
Call the meow() method on this Cat and echo the result.
This is the code created :
<!DOCTYPE html>
<html>
<head>
<title> Challenge Time! </title>
<link type='text/css' rel='stylesheet' href='style.css'/>
</head>
<body>
<p>
<?php
// Your code here
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name ;
public function __construct() {
$cat->name = $name;;
}
public function meow(){
return "Meow meow";
}
}
$cat = new Cat(true ,4 , CodeCat);
echo $cat->meow();
?>
</p>
</body>
</html>
There's three mistakes:
__constructor without parameters
Using undefined variable $cat inside constructor instead of
$this
CodeCat should be string 'CodeCat'
Working code should look something like this:
<?php
// Your code here
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name ;
public function __construct($isAlive,$numLegs,$name) {
$this->name = $name;
$this->isAlive = $isAlive;
$this->numLegs = $numLegs;
}
public function meow(){
return "Meow meow";
}
}
$cat = new Cat(true ,4 , 'CodeCat');
echo $cat->meow();
?>
In your code you have a constructor with no parameters, so $name will be undefined. And when you want to create a new object Cat you call it with 3 params, but you don't have a constructor like that.
What you want is to have a constructor with 1 param $name and call it with that param like this:
<?php
// Your code here
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name ;
public function __construct($name) {
$this->name = $name;
}
public function meow(){
return $this->name;
}
}
$cat = new Cat('CodeCat'); //Like this you will set the name of the cat to CodeCat
echo $cat->meow(); //This will echo CodeCat
?>
Related
I have a function declared in another file. I need to get a variable from it and use it in the class. But for some reason an error appears.
$myvar = myfunc($text);//an error here
class func{
public $title = $myvar;//and here
public function ($title){
...
}
}
You can inject the return value of the function in the constructor when the object is being initialized.
include_once 'func.php';
class Myclass{
public $title;
function __construct( $title = null )
{
$this->title = $title;
}
}
$obj = new Myclass( getVar() );
echo $obj->title;
func.php class
<?php
function getVar()
{
return 'this_var';
}
?>
Your question is about how to use a variable inside a class
class MyClass{
public $title; //do not put a variable here, this is invalid
///you could set a default like this
// e.g. public $title = "Jam";
//this is a setter
public function setTitle(string $title){
$this->title = $title
}
public function getTitle() {
return $this->title;
}
}
then use
$class = new MyClass();
$class->setTitle("jam sponge");
echo $class->getTitle();
or
define a constructor
class MyClass{
public $title;
//this is a constructor
public function __construct(string $title){
$this->title = $title
}
public function getTitle() {
return $this->title;
}
}
then use
$class = new MyClass("jam sponge");
echo $class->getTitle();
the latter is my preference.
As for this $myvar = myfunc($text);//an error here that's not relate to passing the var to the class. You have some other issue in that function, so either show that code or post anew question specific to it
I have a results.php and 2 classes, Dog which extends Pet class. The "fullDescription" method call is just returning null for the results (eg: "Description: Your pet is a named .")
What am I missing?
results.php:
<?php
//include('_includes/pet.class.php');
include("_includes/dog.class.php");
?>
<?php
// COLLECT THE VALUES FROM THE FORM
$petType = $_POST["petType"];
$petName = $_POST["petName"];
// CREATE A NEW INSTANCE OF THE CORRECT TYPE
if ($petType == "dog")
{
$myPet = new Dog();
$myPet->breed = Dog::randomBreed();
}
else
{
$myPet = new Cat();
$myPet->breed = randomBreed();
}
// ASSIGN THE VALUE FROM THE FORM TO THE name PROPERTY OF THE PET OBJECT
$myPet->name = $petName;
$myPet->descriptor = Pet::randomDescriptor();
$myPet->color = Pet::randomColor();
?>
<div class="basic-grey">
<h1>Here's the information about your pet:</h1>
<p>Pet Name: <?php echo $myPet->name; ?></p>
<p>Pet Name: <?php echo $myPet->breed; ?></p>
<p>Pet Name: <?php echo $myPet->color; ?></p>
<p>Pet Name: <?php echo $myPet->descriptor; ?></p>
<p>Description: <?php echo $myPet->fullDescription(); ?> </p>
Pet Class
<?php
class Pet
{
// DEFINE YOUR CLASS PROPERTIES HERE
private $name;
private $descriptor;
private $color;
private $breed;
///////// Getters Setters /////////
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setDescriptor($descriptor) {
$this->descriptor = $descriptor;
}
public function getDescriptor() {
return $this->descriptor;
}
public function setColor($color) {
$this->color = $color;
}
public function getColor() {
return $this->color;
}
public function setBreed($breed) {
$this->breed = $breed;
}
public function getBreed() {
return $this->breed;
}
// DEFINE YOUR METHODS HERE
public function fullDescription()
{
return "Your pet is a $this->descriptor $this->color $this->breed named $this->name.";
//echo $myPet->getName();
}
public static function randomDescriptor()
{
// SET UP AN ARRAY OF VALUES
$input = array("stinky", "huge", "tiny", "lazy", "lovable");
// RETURN A SINGLE RANDOM ELEMENT FROM THE ARRAY
return array_rand(array_flip($input), 1);
}
public static function randomColor()
{
// SET UP AN ARRAY OF VALUES
$input = array("tan", "brown", "black", "white", "spotted");
// RETURN A SINGLE RANDOM ELEMENT FROM THE ARRAY
return array_rand(array_flip($input), 1);
}
}
?>
Dog Class
<?php
include('pet.class.php');
//////////// DOG CLASS //////////////
class Dog extends Pet
{public static function randomBreed()
{
// SET UP AN ARRAY OF VALUES
$input = array("german shepherd", "dachsund", "retriever", "labradoodle", "bulldog");
// RETURN A SINGLE RANDOM ELEMENT FROM THE ARRAY
return array_rand(array_flip($input), 1);
}
}
?>
The problem is because of the following lines,
$myPet->breed = Dog::randomBreed();
and
$myPet->name = $petName;
$myPet->descriptor = Pet::randomDescriptor();
$myPet->color = Pet::randomColor();
You're trying to access private properities of class Pet. Plus, you didn't the assign property values using setter methods. The solution would be like this:
You cannot access private properties of a class from it's child class, or outside of the parent class. First declare them as protected properties:
class Pet
{
// DEFINE YOUR CLASS PROPERTIES HERE
protected $name;
protected $descriptor;
protected $color;
protected $breed;
// your code
}
and then on results.php page change those lines in the following way:
// your code
if ($petType == "dog")
{
$myPet = new Dog();
$myPet->setBreed(Dog::randomBreed());
}
else
{
$myPet = new Cat();
$myPet->setBreed(Cat::randomBreed());
}
$myPet->setName($petName);
$myPet->setDescriptor(Pet::randomDescriptor());
$myPet->setColor(Pet::randomColor());
echo $myPet->fullDescription();
In your Pet class you've set your properties to private which means they cannot be manipulated publicly (from within the application), and only from within the class in which they are set (Pet in this case). Any reason for that?
Set them to public:
public $name;
public $descriptor;
public $color;
public $breed;
Here's the manual on OOP visibility. Discusses the differences between public, protected, private.
In php, i would like to call the initialized properties of the class while calling function with arguments but can't seem to figure it out. Below is my source code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Task 25 NOvember 2015</title>
</head>
<body>
<?php
class Task{
public $name = "abc";
public $fname = "xyz";
public $dob = "10-9-90";
public $country = "country";
public $ddress = "Street";
public $cgpa = 3;
public $degree = "MCS";
public $year = "2014";
public function method1($arg1, $arg2, $arg3){
$this->name = $arg1;
$this->fname = $arg2;
$this->dob = $arg3;
return "My name is ".$this->name." ".", and my father name is ".$this->fname;
//i want to print the above values ... without giving in the function args
}
public function method2($arg4,$arg5){
}
public function method3(){}
public function method4(){}
public function method5(){}
}
$object1 = new Task();
echo $object1->method1("","","");
?>
</body>
</html>
I'm a new php programmer, I would like to figure out how I can make the initialized properties of the class to the function arguments that echo that initialized values when calling functions through objects of that class.
You are replacing the initial values to empty string in you code:
echo $object1->method1("","","");
try :
<?php
class Task
{
public $name = "Naveed";
public $fname = "Zahid";
public $dob = "10-04-1991";
public $country = "Pakistan";
public $ddress = "shergarh mardan kpk";
public $cgpa = 3.83;
public $degree = "MCS";
public $year = "2014";
public function method1($arg1, $arg2, $arg3) {
$this->name = $arg1;
$this->fname = $arg2;
$this->dob = $arg3;
return "My name is " . $this->name . " " . ", and my father name is " . $this->fname;
//i want to print the above values ... without giving in the function args
}
public function method2($arg4, $arg5) {
}
public function method3() {
}
public function method4() {
}
public function method5() {
}
}
$object1 = new Task();
echo $object1->method1("Naveed", "Zahid", "10-04-1991");
?>
Or if you really need to use the initialized values, do not put arguments and do not overwrite the initial values:
<?php
class Task
{
public $name = "Naveed";
public $fname = "Zahid";
public $dob = "10-04-1991";
public $country = "Pakistan";
public $ddress = "shergarh mardan kpk";
public $cgpa = 3.83;
public $degree = "MCS";
public $year = "2014";
public function method1() {
return "My name is " . $this->name . " " . ", and my father name is " . $this->fname;
//i want to print the above values ... without giving in the function args
}
public function method2($arg4, $arg5) {
}
public function method3() {
}
public function method4() {
}
public function method5() {
}
}
$object1 = new Task();
echo $object1->method1();
?>
Also, try to learn more about basic/advance of PHP. you can start using this link: http://www.tutorialspoint.com/php/ tutorialspoint help me alot when studying new language
I am trying to make a basic class that stores a name string variable. The problem is that the setName function is not working properly for me. I am getting the error:
Catchable fatal error: Method TesterClass::__toString() must return a string value in C:\xampp\htdocs\CA18\testerPage.php on line 12
I have tried many different ways of doing this, but nothing seems to fix it: The code is as follows:
<?php
class TesterClass
{
public $name;
public function setName($n)
{
$name = $n;
}
public function __toString()
{
return $this->name;
}
public function __construct()
{
$numArgs = func_num_args();
$args = func_get_args();
if ($numArgs == 0)
{
setName($args[0]);
}
}
}
?>
Here is the class implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Payroll</title>
</head>
<body>
<h1>Payroll</h1>
<?php
require "TesterClass.php";
$myObject = new TesterClass("Philllip");
echo $myObject;
?>
</body>
</html>
Thanks!
Do this:
public function setName($n)
{
$this->$name = $n;
}
$this represents any instance of the class($myObject in your case) while $name alone is a new variable.
I think your check also is wrong.
public function __construct()
{
$numArgs = func_num_args();
$args = func_get_args();
if ($numArgs == 0)//This condition says that there are no args passed so it should give an error
{
//no args
}
else $this->setName($args[0]);
}
In setName() you are setting it to a local variable $name not the $name variable in the class ... you need to use $this->name. You also need to reference $this->setName() and when you check for the number of args, you are looking for when there are 0 ... you should be looking for when there are more than 0.
class TesterClass
{
public $name;
public function setName($n)
{
$this->name = $n;
}
public function __toString()
{
return $this->name;
}
public function __construct()
{
$numArgs = func_num_args();
$args = func_get_args();
if ($numArgs)
{
$this->setName($args[0]);
}
}
}
<?php
class TesterClass
{
public $name = ''; // make sure this is a string!
public function setName($n)
{
$this->name = $n;
}
public function __toString()
{
return $this->name;
}
public function __construct()
{
$numArgs = func_num_args();
$args = func_get_args();
if (count($numArgs)) // if there is an arg!
{
$this->setName($args[0]); // class methods are called with $this!
}
}
}
I dont know why you are using func_get_args, but you could also just use a named parameter, with a default value.
public function __construct($name = '')
{
$this->setName($name);
}
Your code is
public function setName($n)
{
$name = $n;
}
But it should be
public function setName($n)
{
$this->name = $n;
}
In the first code, you are setting a local scope variable named "name" in setName function.
In the last code, you are setting the object property named "name".
Also you should check if it is a valid string value, AND, your property should have an string default value. Otherwise, you may get same error if you did not set name and try to get name.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have found that there are 2 different ways I can display the result of a class method. One by using an object operator, and the other by calling the method as a function. I want to know why and what is best.
Take the following:
<!DOCTYPE html>
<html>
<head>
<title>Cats</title>
<link type='text/css' rel='stylesheet' href='style.css'/>
</head>
<body>
<p>
<?php
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name;
public function __construct($name) {
$this->name = $name;
}
public function meow() {
return "Meio meow";
}
}
$Cat1 = new Cat(CodeCat);
echo $Cat1->meow;
?>
</p>
</body>
</html>
I can alternatively echo the return of the method by:
echo meow($Cat1);
Whats da dealio? Whats better
Thanks for replies!
-Adrian
Ok lets start by using some code that would actually run.
<?php
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name;
public function __construct($name) {
$this->name = $name;
}
public function meow() {
return "Meio meow";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cats</title>
<link type='text/css' rel='stylesheet' href='style.css'/>
</head>
<body>
<p>
<?php
$Cat1 = new Cat('Fluffy');
echo $Cat1->meow();
echo $Cat1->name;
?>
</p>
</body>
</html>
Now because you have defined the cats name property as public public $name; you are allowed to access its value in a totally unrestricted way from any code using this class with either syntax:
$Cat1 = new Cat('Fluffy');
echo $Cat1->name;
//or
echo $Cat1->meow();
//or even set a new value for its name after instantiating it
$Cat1->name = 'Tiddles';
However if you had a property that you didn't want a developer to mess with without being able to check the value first you could define this new property as private so for example 'private $owner;'
Now it is not allowed to use the syntax:
$Cat1->owner = 'Adrian';
because it is a private property, but you still want the user of your class to be able to set a value for the owner property, so you would create a public method like your meow() method that would set the value of this private property but only if it passed some required test like so:
<?php
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name;
private $owner;
public function __construct($name) {
$this->name = $name;
}
public function meow() {
return "Meio meow";
}
public function setOwner($var) {
if ( $var == 'Adrian' || $var == 'Rocky' ) {
$this->owner = $var;
} else {
$this->owner = 'Unknown';
throw new Exception( 'Invalid owners name' );
}
}
}
?>
So you have created a public method to allow access to your private property but only if it meets some specified condition.
Its basiclly a way of controlling access to the properties that require specific values
I suggest you give the documentation a good coat of looking at
as there is also a protected qualifier as well as public and private.