I'm having trouble accessing a class' variable.
I have the functions below in the class.
class Profile {
var $Heading;
// ...
function setPageTitle($title)
{
$this->Heading = $title;
echo 'S: ' . $this->Heading;
}
function getPageTitle2()
{
echo 'G: ' . $this->Heading;
return $this->Heading;
}
// ...
}
Now when I run the method $this->setPageTitle("test") I only get
G: S: test
What's wrong with the getPageTitle2 function? Heading is public btw. Please help!
Thanks guys!
Now when I run the method $this->setPageTitle("test") I only get
G: S: test
That sounds implausible. Are you sure you're not running:
$this->getPageTitle2();
$this->setPageTitle("test");
PHP - like most programming languages - is an imperative language. This means that the order in which you do things matters. The variable $this->Header is not set at the time where you call getPageTitle2.
If you have "G: S: test"
it means you called getPageTitle2 before setPageTitle !
It looks normal then : I suggest first set then get.
you have to declare the Heading and title out of the function ... i dont know if you already did that
see the order of calling the functions
class Profile {
var $Heading;
// ...
function setPageTitle($title)
{
$this->Heading = $title;
echo 'S: ' . $this->Heading;
}
function getPageTitle2()
{
echo 'G: ' . $this->Heading;
return $this->Heading;
}
// ...
}
I am guessing you are doing something like this:
$profile = new Profile();
$profile->setPageTitle("test");
$profile->getPageTitle2();
and that this would result in the following output:
S: testG: test
and that if you echo $profile you will just get
test
so what do you think is the problem or what are you not accomplishing that you want to?
also I would probably declare $Heading as
private $heading;
Related
I have this in my model called B:
public function getA() {
return $this->hasOne(\app\models\A::className(), ['id' => 'A_Id']);
}
public function getDispName() {
return $this->a->attr . ' ' . $this->attr . ' ' . $this->attr2;
}
works everything fine, until I go to Create. Then I get the following "error":
PHP Notice – yii\base\ErrorException Trying to get property of non-object
As a workaround I have done this:
public function getDispName() {
if (is_object($this->a)) {
return $this->a->attr . ' ' . $this->attr . ' ' . $this->attr2;
}
}
I'm not sure if this is a good solution, or why do I get this "notice" only at create, but I would like to understand and do it correctly. I don't want this to cause problems somewhere else. Maybe I miss something other basic and important knowledge. If you have any ideas, I would be grateful to hear it. Thanks.
You are probably trying to use a B model that does not have a A model attached. If that is the case of course your function would fail. Are you sure for every B you have an A? Probably you are inserting a B and not inserting an A and trying to show info on it.
Your options are:
1) do exactly like you did, maybe change it to
public function getDispName() {
$display = '';
if (is_object($this->a)) {
$display = $this->a->attr;
}
return $display . ' ' . $this->attr . ' ' . $this->attr2;
}
2) fix your code to always make sure you insert an A when you insert a B. It can be an empty record but it has to be a record.
This property is based on others properties, so when you create new object of type A you don't need to indicate this property. Indicate only fields from which it consists.
Open /views/model_name/_form.php and delete row with property dispName
<?= $form->field($model, 'dispName')->textInput() ?> // or textarea or ...
I have created my own little PHP framework for fun, however, I am having trouble passing variables from bootstrap to the views....
if I put an echo,print_r,var_dump my target variable in the bootstrap, the output is displayed in the browser before the tag... yet the target var in bootstrap.php is not available in the view, it is coming up as "" even though at the top of the page it is being output correctly....
Somethings I noticed from similar questions:
- The target variable is not being over written
- The include target path is correct and the file exists
- The file is only being included one time (include_once is only fired once)
Any ideas are greatly appreciated, I am pulling my hair out over here lol...
Source Code
https://gist.github.com/jeffreyroberts/f330ad4a164adda221aa
If you just want to display your site name, I think you can use a constant like that :
define('SITE_NAME', "Jeff's Site");
And then display it in your index.tpl :
<?php echo SITE_NAME; ?>
Or, you can send your variables to the view by extending a little bit your JLR_Core_Views :
class JLR_Core_Views
{
private $data;
public function loadView($templatePath, $data = array())
{
$this->data = $data;
$templatePath = JLR_ROOT . '/webroot/' . $templateName . '.tpl';
if(file_exists($templatePath)) {
// Yes, I know about the vuln here, this is just an example;
ob_start();
include_once $templatePath;
return ob_get_clean();
}
}
function __get($name)
{
return (isset($this->data[$name]))
? $this->data[$name]
: null;
}
}
Then, you can call your template like that :
$view = new JLR_Core_Views();
$view->loadView("index", array("sitename" => "Jeff's Site"));
And here is your index.tpl :
<?php echo $this->siteName; ?>
Below is another example of what you can do.
First, you create this class in order to store all the variables you want :
<?php
class JLR_Repository {
private static $data = array();
public function set($name, $value) {
self::$data[$name] = $value;
}
public function get($name) {
return (isset(self::$data[$name]))
? self::$data[$name]
: null;
}
}
?>
Then, when you want to store something in it :
JLR_Repository::set("sitename", "Jeff's Site");
And in your index.tpl :
<?php echo JLR_Repository::get("sitename"); ?>
try using the 'global' keyword - http://php.net/manual/en/language.variables.scope.php
<?php
class oopClass{
function __construct($editingtext, $searchfor, $replacewith){
if(!empty($editingtext) && !empty($searchfor) && !empty($replacewith)){
$editingtext = str_replace($searchfor,$replacewith,$editingtext);
echo $editingtext;
}else{
echo 'All Fields Are Required.';
}
}
}
//closing php
The code is working , but as there is no properties of the class are set which is a bad practice, which variables of this code should be set as a class property and why?
There are other things wrong with your code, and it is not the absence of properties. You are constructing an object and in the constructor you output the result. THAT is bad practice.
I'd fix it something like this:
class TextReplacer {
var $search;
var $replace;
function __construct($s, $r) {
$this->search = $s;
$this->replace = $r;
}
function replace($text) {
// your code, using the properties for search and replace, RETURNING the result
return $ret;
}
}
then call like:
$oo = new TextReplacer("bar", "baz");
echo $oo->replace("let's replace some bars in here");
In short:
Nothing wrong with not using properties, if your class is designed like that.
Please use useful class, method and variable names.
Don't do more than one thing in a method ("side effects").
Don't output the result, but return it. It is up to the user of the class to decide what happens to the results.
(most importantly): Think before you code.
It's not necessarily bad practice if the above code is ALL you plan on doing with this code. If you needed to expand its functionality, I might imagine $editingtext could be a property.
class oopClass{
private $editingtext;
function __construct($editingtext, $searchfor, $replacewith){
$this->editingtext = $editingtext;
if(!empty($this->editingtext) && !empty($searchfor) && !empty($replacewith)){
$this->editingtext = str_replace($searchfor,$replacewith,$this->editingtext);
echo $this->editingtext;
}else{
echo 'All Fields Are Required.';
}
}
}
//closing php
Hi Im new to PHP so forgive the basic nature of this question.
I have a class: "CustomerInfo.php" which Im including in another class. Then I am trying to set a variable of CustomerInfo object with the defined setter method and Im trying to echo that variable using the getter method. Problem is the getter is not working. But if I directly access the variable I can echo the value. Im confused....
<?php
class CustomerInfo
{
public $cust_AptNum;
public function _construct()
{
echo"Creating new CustomerInfo instance<br/>";
$this->cust_AptNum = "";
}
public function setAptNum($apt_num)
{
$this->cust_AptNum = $apt_num;
}
public function getAptNum()
{
return $this->cust_AptNum;
}
}
?>
<?php
include ('CustomerInfo.php');
$CustomerInfoObj = new CustomerInfo();
$CustomerInfoObj->setAptNum("22");
//The line below doesn't output anything
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
//This line outputs the value that was set
echo "CustomerAptNo = $CustomerInfoObj->cust_AptNum<br/>";
?>
Try
echo 'CustomerAptNo = ' . $CustomerInfoObj->getAptNum() . '<br/>';
Or you will need to place the method call with in a "Complex (curly) syntax"
echo "CustomerAptNo = {$CustomerInfoObj->getAptNum()} <br/>";
As your calling a method, not a variable with in double quotes.
for concat string and variables, you can use sprintf method for better perfomace of you app
instead of this:
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
do this:
echo sprintf("CustomerAptNo = %s <br />", $CustomerInfoObj->getAptNum());
check http://php.net/sprintf for more details
Why PHP class does not return <h1>404</h1><p>Not found</p>?
class checkid{
public $title;
public $content;
function status(){
$this->title='404';
$this->content='Not found';
}
}
$checkid=new checkid($url);
//$id=0;
((isset($id)) ? '' : $checkid->status().$title=$checkid->title.$content=$checkid->content);
//Why it does not return `<h1>404</h1><p>Not found</p>`?
echo "<h1>$title</h1><p>$content</p>";
Update:
I know well to do it trough
if(isset($id)){}else{
$checkid->status();
$title=$checkid->title;
$content=$checkid->content);
}
but I was worndering if it is possible to make it trough using
((isset($id)) ? '' : $checkid->status().$title=$checkid->title/*here $content break it down*//*.$content=$checkid->content*/);
Change isset('id') to isset($id).
The reason why you were getting <h1>404Not found</h1><p>Not found</p> was because you were concatenating the value of $content to the value of $title.
Also, you're code is quite a mess. I took the liberty of cleaning it up a bit:
class checkid
{
public $title;
public $content;
function status()
{
$this->title='404';
$this->content='Not found';
}
}
$checkid=new checkid($url);
//$id=0;
if(!isset($id))
{
$checkid->status();
$title=$checkid->title;
$content=$checkid->content;
}
echo "<h1>$title</h1><p>$content</p>";
You don't assign $title and $content
You probably want something like this
$checkid->status();
echo "<h1>$checkid->title</h1><p>$checkid->content</p>";
Because you are trying to (ab)use a conditional expression as a if statement.
if(!isset($id))
{
$checkid->status();
$title = $checkid->title;
$content = $checkid->content;
}
What isset('id') means? do you mean isset($id) or isset($_GET['id']) ?
And, btw,
$checkid->status().$title=$checkid->title.$content=$checkid->content);
is nonsens: you attach the return of status() to $checkid AND YOU ATTACH $title which is made equal to $checkid->title CONCATENATED to $content, and everythin is assigned $checkid->content
A bit confusing there