I am a beginner in php. I want to call a class within the same php file but when i am trying the class itself is not recognized. What i am doing wrong. please guide me through the right direction since i just started writing code in php.
Code:
<?php
$details = new studdetails();
$details->id = $sid;
$details->name = $sname;
$details->roll = $sroll;
Somemethod("Have some calculations over here");
Class studdetails{
public id;
public name;
public roll;
}
?>
There are some syntax errors. Missing ";" and "$".
<?php
Class studdetails {
public $id;
public $name;
public $roll;
}
$details = new studdetails();
$details->id = $sid;
$details->name = $sname;
$details->roll = $sroll;
?>
In php you need to prefix class properties with $ sign.
See the example bellow
$sid = 1;
$sname = 'name';
$sroll = 'sroll';
$details = new studdetails();
$details->id = $sid;
$details->name = $sname;
$details->roll = $sroll;
Somemethod("Have some calculations over here", $details);
Class studdetails
{
public $id;
public $name;
public $roll;
}
function Somemethod($str, $obj) {
echo $str . PHP_EOL;
var_export($obj);
}
Related
I am trying to get a dynamic variable value in a PHP class but not sure how to do this. Here's my code:
<?php
class Test
{
public $type = "added";
public $date_added;
public function set_status()
{
$this->date_added = "Pass";
}
public function get_status()
{
echo $this->date_{$type};
}
}
$test = new Test();
$test->set_status();
$test->get_status();
?>
I am getting following error:
Notice: Undefined property: Test::$date_ in...
Notice: Undefined variable: type in ...
If I write echo $this->date_added; in place of echo $this->date_{$type}; then I get output "Pass".
How to fix it and do it properly?
Since you're using variable variables, put them in quotes, then concatenate:
echo $this->{'date_' . $this->type};
// not $type, use `$this->` since it's part of your properties
Or using via formatted string (double quotes will work as well):
echo $this->{"date_{$this->type}"};
<?php
class Test
{
public $type = "added";
public $date_added;
public function set_status()
{
$this->date_added = "Pass";
}
public function get_status()
{
echo $this->{'date_' . $this->type};
}
}
$test = new Test();
$test->set_status();
$test->get_status();
?>
You can do it multiple ways, date_{$type} is not valid expression and to acccess the class property you have to use this keyword .
class Test
{
public $type = "added";
public $date_added;
public function set_status()
{
$this->date_added = "Pass";
}
public function get_status()
{
$prop = 'date_'.$this->type;
echo $this->{'date_'.$this->type}; # one way to do it
echo $this->$prop; # another way to do it
echo $this->{"date_{$this->type}"}; # another way to do it
}
}
$test = new Test();
$test->set_status();
$test->get_status();
I'm trying to print a property of the simple class below. But instead i get the error above. I haven't found an answer on similar questions on here. The error triggers on this line:
echo "$object1 name = " . $object1->name . "<br>";
Using XAMPP on Windows Help?
<?php
$object1 = new User("Pickle", "YouGotIt");
print_r($object1);
$object1->name = "Alice";
echo "$object1 name = " . $object1->name . "<br>"; /* this triggers the error */
class User
{
public $name, $password;
function __construct($n, $p) { // class constructor
$name = $n;
$password = $p;
}
}
?>
There are two things wrong in your code,
You're using local variables in your class constructor, not instance properties. Your constructor method should be like this:
function __construct($n, $p) {
$this->name = $n;
$this->password = $p;
}
Now comes to your error, Object of class could not be converted to string. This is because of this $object in echo statement,
echo "$object1 name = " ...
^^^^^^^^
You need to escape this $object1 with backslash, like this:
echo "\$object1 name = " . $object1->name . "<br>";
In my case the problem was the way I was initializing the class variable.
This was my code :
public function __construct(User $userObj) {
$this->$userObj = $userObj;
}
and I solved it by changing it to the following :
public function __construct(User $userObj) {
$this->userObj = $userObj;
}
The line in the first snippet caused the problem : $this->$userObj = $userObj
How do I initialize objects inside a function within a class? so I can call each object like page[0]->getTitle(); or page[1]->getDescription();
The error now says :
Fatal error: Using $this when not in object context in C:\xampp\htdocs\class.page.php on line 92
index.php
Page::createObjects();
and my page.class.php
private title;
private description;
private page;
public function __construct($title="", $description=""){
$this->title = $title;
$this->description = $description;
}
public static function createObjects(){
$database = new database();
$database->query('SELECT * FROM pages');
for($i=0;$i<$totalRows;$i++){
//line 92 here
$this->page[$i] = new self("Title", "Description");
}
}
You might consider having two different classes here, Page (page.class.php) and Pages (pages.class.php). Your Page class will represent an individual page record from your database, and your Pages class will contain methods that work on a set of records.
page.class.php
<?php
class Page
private title;
private description;
public function __construct($title="", $description=""){
$this->title = $title;
$this->description = $description;
}
public function getTitle()
{
return $this->title;
}
public function getDescription()
{
return $this->description();
}
}
?>
pages.class.php
<?php
class Pages
public static function createObjects(){
$pages = array();
$database = new database();
$database->query('SELECT * FROM pages');
for($i=0;$i<$totalRows;$i++){
//line 92 here
$pages[] = new Page("Title", "Description");
}
return $pages;
}
}
?>
Then in your index.php, you get your Page objects from Pages
index.php
<?php
$pages = Pages::createObjects();
// to get the title of the first object
echo $pages[0]->getTitle();
?>
Like others commented, you can't access $this from a static function
a static field/variable/property/method belong to the class, not to a specific instance
<?php
class VIP
{
private $name, $surname;
private static $vips = array();
function __construct($name, $surname){
$this->name = $name;
$this->surname = $surname;
self::$vips[] = $this;
}
function getCredentials(){
return $this->name . ", " . $this->surname;
}
static function getAll(){
return self::$vips;
}
}
$a = new VIP("George", "Clooney");
$b = new VIP("Scarlet", "Johansson");
$c = new VIP("Brad", "Pitt");
$d = new VIP("Emma", "Stone");
echo $a->getCredentials() . "\n";
foreach(VIP::getAll() as $vip)
echo $vip->getCredentials() . "\n";
?>
demo: https://eval.in/161874
however, this is more than likely bad code, since you are a beginner you should forget of static fields and methods and just use regular ones
better code:
<?php
class VIP
{
private $name, $surname;
function __construct($name, $surname){
$this->name = $name;
$this->surname = $surname;
}
function getCredentials(){
return $this->name . ", " . $this->surname;
}
}
class VIPsList
{
private $storage = [];
function add(VIP $vip){
$this->storage[] = $vip;
}
function getAll(){
return $this->storage;
}
}
$a = new VIP("George", "Clooney");
$b = new VIP("Scarlet", "Johansson");
$c = new VIP("Brad", "Pitt");
$d = new VIP("Emma", "Stone");
$collection = new VIPsList();
$collection->add($a);
$collection->add($b);
$collection->add($c);
$collection->add($d);
echo $a->getCredentials() . "\n";
foreach($collection->getAll() as $vip)
echo $vip->getCredentials() . "\n";
?>
https://eval.in/161898
Consider the following code:
class Project
{
public $ProjectID;
}
class Work
{
public $WorkID;
}
public function insert($pData, $tableName)
{
//generate insert here
$pData->{$tableName . 'ID'} = $result->getId();
}
$p = new Project();
$w = new Work();
insert($w, 'Work');
insert($p, 'Project');
echo $p . ' -- ' . $w;
Now how would I go about setting the variable in a dynamic way? I'm building a data layer. The $pData->{$tableName . 'ID'} doesn't seem to work...
So, you want to dynamically call setters?
$y = new stdClass();
$y->prop1 = "something";
$targetProperty = "prop1";
$y->$targetProperty = "something else";
echo $y->prop1;
//Echos "something else"
That what you're looking for?
This is what you're looking for:
public function set_to_seven($p_data, $name)
{
$name = $name . 'ID';
$p_data->$name = 7;
}
The property name can be a variable. Just like functions:
$p = 'print_r';
$p('StackOverflow');
For future reference: if you need this statically, you're looking for variable variables,
public function set_to_seven($p_data, $name)
{
$name = $name . 'ID';
$p_data::$$name = 7;
}
You can set public properties by accessing them just like any other definition in the class.
$p = new Project();
$p->ProjectID = 5;
echo $p->ProjectID; // prints 5
http://php.net/manual/en/language.oop5.visibility.php
This worked for me.
class Project {
public $ProjectID;
}
function setToSeven($pData, $name) {
$pData->{$name . "ID"} = 7;
}
$p = new Project();
setToSeven($p, 'Project');
echo $p->ProjectID;
You just need to echo the variable or set up a toString function on the class to echo the class. To String works like this
class Project {
public $ProjectID;
public function __toString(){
return (string)$this->ProjectID;
}
}
function setToSeven($pData, $name) {
$pData->{$name . "ID"} = 7;
}
$p = new Project();
setToSeven($p, 'Project');
echo $p;
I have a function w/in a function, and I need the inner function to make it's variables available in a scope of parent function, e.g.:
function sayMyName(){
getName(); // inner function generates $name value
echo $name; // use $name
}
sayMyName();
I could easily just globalize things w/in both functions... But my situation is far more complicated and handles more variables and globalizing each one is a bit tedious.
Thanks.
PS
i noticed a lot of "return" suggestions. sorry i wasnt clear , i need to return more variables.. not a simple return. thanks guys
You may use $_GLOBALS, but it`s a "bad practice". So,
1: Use return:
<?php
function getName(){
$name = 'Smith';
return $name;
}
function sayMyName(){
$name = getName();
echo $name;
}
sayMyName();
?>
Shows:
Smith
2: Use references:
<?php
function getName(&$name){
$name = 'Smith';
}
function sayMyName(){
getName($name);
echo $name;
}
sayMyName();
?>
Shows:
Smith
3: Return array for multiple variables:
<?php
function getName(){
$surname = 'Smith';
$name = 'John';
return array($surname, $name);
}
function sayMyName(){
list($surname, $name) = getName();
echo $name, ' ', $surname;
}
sayMyName();
?>
Shows:
John Smith
4. Return custom object for multiple variables:
<?php
function getName(){
$surname = 'Smith';
$name = 'John';
$buffer = new stdClass();
$buffer->name = $name;
$buffer->surname = $surname;
return $buffer;
}
function sayMyName(){
$obj = getName();
echo $obj->name, ' ', $obj->surname;
}
sayMyName();
?>
Shows:
John Smith
5. Use anonymous function with use statement and references:
<?php
function sayMyName(){
$surname = $name = 'Unknown';
$temp = function() use (&$name, &$surname){
$surname = 'Smith';
$name = 'John';
};
$temp();
echo $name, ' ', $surname;
}
sayMyName();
?>
Shows:
John Smith
do this
function sayMyName(){
$name = getName(); // inner function generates $name value
echo $name; // results will be returned
}
sayMyName();
I hope your inner function is returning name like this
function getName(){
return $name;
}
then it will work
This is what the object oriented programming was designed for. If many functions should share variables, it is probably best to encapsulate them to class like this:
class WhateverDescibestYourViewOfTheWorld {
protected $name;
function __construct( $name)
{
$this->name = $name;
}
function GetName() {
return $this->name;
}
function SayName()
{
echo $this->name;
}
}
// And use it:
$o = new WhateverDescibestYourViewOfTheWorld();
...
$o->SayName();
Or you can build class which will be just used as data container:
class DataContainer {
public $name;
public $address;
// ...
}
// By reference this will modify object previously created
function GetProperties( &$dataContainer) // Note that & isn't necessary since PHP5
{
$dataContainer->name = "...";
}
$c = new DataContainer();
GetProperties($c);
Or you can simplify this and use array:
function GetProperties( array &$dataContainer)
{
$dataContainer['name'] = '...';
}
$data = array();
GetProperties($data);
What about first assigning the return value of getName() to a variable?
$name = getName();
If you only need one variable you can do this
function getName(){
// Some code
return 'my name is XXX';
}
function sayMyName(){
$name = getName(); // inner function generates $name value
echo $name; // results to undefined
}
sayMyName();
Otherwise you may consider using a class : http://www.php.net/manual/en/language.oop5.php
You can use references
$param = "aaa";
function f(&$param)
{
//dostuff
inner($param);
echo $param;
}
function inner(&$inner) { //do other stuff }
or use return value
function f() { echo inner(); }
function inner($param) {return $param;}
if you work on references, both functions will work on same variable, not on a copy
http://php.net/manual/en/language.references.php
the best way would be with class
<?php
class Person
{
private $name;
public function setName($name){ $this->name = $name;}
public function sayName() {echo $this->name;}
}
$person = new Person();
$person->setName("Robert");
$person->sayName();
It's good way to make it in OOP.
That what you are thinking is wrong, however you can return an array of values. For ex:
function sayMyName()
{
$result = getName(); // inner function creates an array
echo $result['name'];
}
or better an object:
class Results
{
public $name;
}
function sayMyName()
{
$result = getName(); // inner function creating an object
echo $result->name;
}
You can also do it as below.
$name = "";
function sayMyName(){
getName(); // inner function generates $name value
//set $name variable inside getName() function.
echo $name; // results to undefined
}
sayMyName();
Please use bellow code ,it will solve your problem
global $var;
You can use it anywhere within your php span.